////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity.groups.stock;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import cc.mango.android.chart.StkTimeView;
import cc.mango.common.FinalKey;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.DBHelper;
import cc.telecomdigital.tdstock.DefaultClickHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.LightStreamerHandlerInterface;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Rotate3dAnimation;
import cc.telecomdigital.tdstock.StringUtils;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.WebViewHelper;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.INetworkChangeListener;
import cc.telecomdigital.tdstock.Services.LS_Authentication.LS_Authentication_Result;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeVerify.ITDStockReqFreeVerify_Result;
import cc.telecomdigital.tdstock.Services.TDStockReqFreeVerify.TDStockReqFreeVerify_Result;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.AboutActivity;
import cc.telecomdigital.tdstock.activity.AccountLoginActivity;
import cc.telecomdigital.tdstock.activity.ChangePortraitAndLandscapeActivity;
import cc.telecomdigital.tdstock.activity.DeclareTrialActivity;
import cc.telecomdigital.tdstock.activity.DisclaimersActivity;
import cc.telecomdigital.tdstock.activity.RealtimeStockActivity;
import cc.telecomdigital.tdstock.activity.RegisterActivity;
import cc.telecomdigital.tdstock.activity.VerifyActiveCodeActivity;
import cc.telecomdigital.tdstock.activity.chart.StkChartActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.MonitorUtil;
import cc.telecomdigital.tdstock.activity.groups.monitor.util.SaveBookMarkAsyncTask;
import cc.telecomdigital.tdstock.activity.groups.more.StockStarIndexActivity;
import cc.telecomdigital.tdstock.model.IndexFuturesInfo;
import cc.telecomdigital.tdstock.model.IndexInfo;
import cc.telecomdigital.tdstock.model.StockInfo;
import cc.telecomdigital.tdstock.model.TimestampInfo;
import cc.telecomdigital.tdstock.model.WorldIndexDelayInfo;
import cc.telecomdigital.tdstock.model.WorldIndexInfo;
import cc.telecomdigital.tdstock.trading.Trade_LoginActivity;
import cc.telecomdigital.tdstock.trading.Trade_OrderKeypadActivity;
import cc.telecomdigital.tdstock.trading.Trade_tradingOptionActivity;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.view.SunFlowerView;
import cc.telecomdigital.tdstock.view.TextFitTextView;

import com.lightstreamer.ls_client.UpdateInfo;

/**
 * including: [world] index, index futures, stock information
 * 
 * @author haibo
 */
public class CurrentStockInfoActivity extends
		ChangePortraitAndLandscapeActivity implements View.OnClickListener,
	OnEditorActionListener, ILS_UserClient_Response, INetworkChangeListener
/* Andy */
// ,CdrSender
{
	// changed by zhengan

	private String						TAG								= CurrentStockInfoActivity.class
																			.getSimpleName();
	private final static String			DELAY_TIPS						= "延遲逾<br>15分鐘";
	// private final static String BRACKET = "(&nbsp;)&nbsp;";
	private final static String			DELAY_TIPS_BROKER_QUEUE				= "經紀名稱及編號 樣本<br>Broker Queue Sample";		// "經紀名稱及編號<br>Broker Queue";
	private final static String			DELAY_TIPS_STOCK_MARKET_DEPTH			= "市場深度 樣本<br>Market Depth Sample";		// "市場深度<br>Market Depth";
	private final static String			DELAY_TIPS_STOCK_TRADETICKER_QUEUE		= "交易記錄 樣本<br>Trade Ticket Sample";		// "交易記錄<br>Trade Ticket";

	private final static int				SPREAD_COUNTER						= 20;
	private final static long			UPDATE_STOCK_INFO_INTERVAL			= 6000l;								// 6
																										// seconds

	private static NumberFormat			_formaterOnSacle2;
	private static NumberFormat			_formaterOnSacle1;
	private static TextView[]			_BID_LEFT_TEXTVIEWS					= new TextView[SPREAD_COUNTER];
	private static TextView[]			_BID_RIGHT_TEXTVIEWS				= new TextView[SPREAD_COUNTER];
	private static TextView[]			_ASK_LEFT_TEXTVIEWS					= new TextView[SPREAD_COUNTER];
	private static TextView[]			_ASK_RIGHT_TEXTVIEWS				= new TextView[SPREAD_COUNTER];

	private static TextView[]			_BID_LEFT_TEXTVIEWS_CH				= new TextView[SPREAD_COUNTER];
	private static TextView[]			_BID_RIGHT_TEXTVIEWS_CH				= new TextView[SPREAD_COUNTER];
	private static TextView[]			_ASK_LEFT_TEXTVIEWS_CH				= new TextView[SPREAD_COUNTER];
	private static TextView[]			_ASK_RIGHT_TEXTVIEWS_CH				= new TextView[SPREAD_COUNTER];

	private static TextFitTextView[][]		_tradeticker_textviews				= new TextFitTextView[5][4];

	public static String				_stockCode;
	public static String				_lastStockCode						= "1";
	public static boolean				_isNewStock						= false;

	private static final String			STOCK_NOT_FOUND_MSG					= "not found";

	private Button						_toolbutton_news;
	private Button						_toolbutton_wc;
	private Button						_toolbutton_search;
	private Button						_toolbutton_backWarrantResult;
	private Button						_toolbutton_addstock;

	private ViewGroup					_current_stock_bid;

	private TextView					_index_hsi;
	private TextView					_index_his_net;
	private TextView					_index_his_turnover;

	private TextView					_index_phsi;
	private TextView					_index_phsi_net;

	private TextView					_index_futures_hsi_1;
	private TextView					_index_futures_hsi_1_net;

	private TextView					_index_futures_hsi_2;
	private TextView					_index_futures_hsi_2_net;

	private TextView					_worldindex_sse1;
	private TextView					_worldindex_sse1_net;

	private TextView					_server_time;

	private EditText					_current_stock_code;
	private TextView					_current_stock_chinese_short_name;
	private TextView					_current_stock_nominal;

	private ImageView					_up_down;
	private TextView					_current_stock_net;
	private TextView					_current_stock_net_percentage;

	private TextView					_current_stock_sharetraded;
	private TextView					_current_stock_turnover;
	private TextView					_current_stock_prevcloseprice;
	private TextView					_current_stock_openprice;
	private TextView					_current_stock_highprice;
	private TextView					_current_stock_lowprice;

	private TextView					_current_stock_bidprice;
	private TextView					_current_stock_askprice;

	private TextView					_current_stock_bid_share_1;
	private TextView					_current_stock_bid_share_2;
	private TextView					_current_stock_bid_share_3;
	private TextView					_current_stock_bid_share_4;
	private TextView					_current_stock_bid_share_5;

	private TextView					_current_stock_bid_queue_1;
	private TextView					_current_stock_bid_queue_2;
	private TextView					_current_stock_bid_queue_3;
	private TextView					_current_stock_bid_queue_4;
	private TextView					_current_stock_bid_queue_5;

	private TextView					_current_stock_ask_share_1;
	private TextView					_current_stock_ask_share_2;
	private TextView					_current_stock_ask_share_3;
	private TextView					_current_stock_ask_share_4;
	private TextView					_current_stock_ask_share_5;

	private TextView					_current_stock_ask_queue_1;
	private TextView					_current_stock_ask_queue_2;
	private TextView					_current_stock_ask_queue_3;
	private TextView					_current_stock_ask_queue_4;
	private TextView					_current_stock_ask_queue_5;

	private TextView					_current_stock_lotsize;
	private TextView					_current_stock_ex_ymd;
	private TextView					_current_stock_year_high;
	private TextView					_current_stock_div_ymd;

	private TextView					_current_stock_year_low;
	private TextView					_current_stock_div_value;
	private TextView					_current_stock_profitpershare;
	private TextView					_current_stock_rate_of_return;

	private TextView					_current_stock_currency;
	private TextView					_current_stock_pe;
	private TextView					_current_stock_day_10_avg;

	private TextView					_current_stock_rsi9;
	private TextView					_current_stock_day_20_avg;
	private TextView					_current_stock_rsi14;
	private TextView					_current_stock_day_50_avg;

	private TextView					_current_stock_day_100_avg;
	private TextView					_current_stock_day_200_avg;
	private TextView					_current_stock_day_250_avg;

	private TextView					_chart_mask;

	private LinearLayout				_broker_bid_queue_spread_left;
	private LinearLayout				_broker_bid_queue_spread_right;

	private LinearLayout				_broker_ask_queue_spread_left;
	private LinearLayout				_broker_ask_queue_spread_right;

	private LinearLayout				_broker_bid_queue_spread_left_ch;
	private LinearLayout				_broker_bid_queue_spread_right_ch;

	private LinearLayout				_broker_ask_queue_spread_left_ch;
	private LinearLayout				_broker_ask_queue_spread_right_ch;

	private ViewGroup					_mContainer;
	private LinearLayout				_broker_queue_name;
	private LinearLayout				_broker_queue_code;
	private StkTimeView					_stkTimeView;

	private static final String			MESSAGE_KEY_INDEX_NAME				= "index";

	private static final String			INDEX_NAME_HSI						= "HSI";
	private static final String			INDEX_NAME_HSCEI					= "HSCEI";

	private static final String			INDEX_FUTURES_HSI_1					= "HSI:1";
	private static final String			INDEX_FUTURES_HSI_2					= "HSI:2";

	private static final String			WORLDINDEX_SSE1					= "SSE1 ";

	private SharedPreferences			_prefsStockCode;
	private static final int				MESSAGE_HANDLE_ID					= 800;
	private static final int				MESSAGE_HANDLE_ID_UPDATE_BACKGROUND	= MESSAGE_HANDLE_ID + 500;
	private static final int				MESSAGE_HANDLE_ID_UPDATE_BACKGROUND_NET	= MESSAGE_HANDLE_ID_UPDATE_BACKGROUND + 1;

	private static final int				VIEW_BID_SPREAD_ID_START_LEFT			= 62000000;
	private static final int				VIEW_BID_SPREAD_ID_START_RIGHT		= 63000000;
	private static final int				VIEW_ASK_SPREAD_ID_START_LEFT			= 64000000;
	private static final int				VIEW_ASK_SPREAD_ID_START_RIGHT		= 65000000;

	private static final int				VIEW_BID_SPREAD_ID_START_LEFT_CH		= 66000000;
	private static final int				VIEW_BID_SPREAD_ID_START_RIGHT_CH		= 67000000;
	private static final int				VIEW_ASK_SPREAD_ID_START_LEFT_CH		= 68000000;
	private static final int				VIEW_ASK_SPREAD_ID_START_RIGHT_CH		= 69000000;

	private static String				IDENTIFIER_0						= CurrentStockInfoActivity.class
																			.getSimpleName()
																			+ "00";
	private static String				IDENTIFIER_1						= CurrentStockInfoActivity.class
																			.getSimpleName()
																			+ "01";
	private static String				IDENTIFIER_2						= CurrentStockInfoActivity.class
																			.getSimpleName()
																			+ "02";
	private static String				IDENTIFIER_3						= CurrentStockInfoActivity.class
																			.getSimpleName()
																			+ "03";
	private static String				IDENTIFIER_4						= CurrentStockInfoActivity.class
																			.getSimpleName()
																			+ "04";
	// private static String IDENTIFIER_5 =
	// CurrentStockInfoActivity.class.getSimpleName() + "05";

	private CallbackHandlerOnStock		_callBackHandlerOnStock;
	private static CustomizeDialog		_entryErrordialog;
	private CustomizeDialog				_callbackErrMsgdialog;

	private boolean					_isWarrant;
	private TableRow					_rowForWarrant;
	private String[][]					_res4ReplaceMent;
	private TextView[]					_label4ReplaceMent;
	private TextView[]					_field_value_4ReplaceMent;

	private TextView					_field_current_stock_call_put;
	private TextView					_field_current_stock_gearing;

	// modify by zor(ouyangzhihui)
	private ImageView					_img_logo;
	/* Andy */
	// private static StreamerTimeoutHandler _streamerTimeoutHandler;
	// private boolean _isTradingTime;
	// private Context _context;
	// private CdrHelper _cdrHelper;

	private CallbackHandlerOnIndex		_callbackHandlerOnIndex;
	private CallbackHandlerOnIndexFutures	_callbackHandlerOnIndexFutures		= null;
	private CallbackHandlerOnWorldIndex	_callbackHandlerOnWorldIndex			= null;
	private CallbackHandlerOnTimeServer	_callbackHandlerOnTimeServer			= null;
	/* Andy */
	// private CallbackHandlerOnSyncTradingTime
	// _callbackHandlerOnSyncTradingTime = null;

	// by zor(ouyangzhihui)
	private LinearLayout				_buy_waiting;
	private SunFlowerView				sunFlowerView1;

	// private boolean _hasSubscribedItems;
	private String[]					_securities_company_code;
	private String						_securities_company_name;
	private ScrollView					_scrollview;

	/* Andy */
	// private SubscribedTableKey _identityForsubscribedStock; //by haibo,
	// 2011-07-13

	// /////////////////////by ouyangzhihui
	// 2011-7-8////////////////////////////////////
	private Animation					anim_down							= null;
	private Animation					anim_up							= null;

	public LinearLayout					container_input;
	private TextView					editTextView;

	private void dealwithEnterCode(int number)
	{
		String tmp = _current_stock_code.getText().toString();
		switch (number)
		{
			case 10: // ok
				if (tmp.length() > 0)
				{
					_current_stock_code.setText(String.valueOf(Integer
							.parseInt(tmp, 10)));
					_current_stock_code.clearFocus();
				}
				container_input.startAnimation(anim_up);
				// If there is no network, create a prompt
				if (!SystemInfo
						.isNetworkingConnected(CurrentStockInfoActivity.this))
				{
					new CustomizeDialog(
							CurrentStockInfoActivity.this
									.getMyOwnContext(),
							getResources().getString(R.string.info),
							getResources()
									.getString(
											R.string.networking_disconnect_tips))
					{
						@Override
						public void onClick(View v)
						{
							if (v == okButton)
							{
								dismiss();
								_current_stock_code
										.setText(lastStockCode);
								// _current_stock_code.setSelection(_current_stock_code.getText().toString().length());
								_current_stock_code.clearFocus();
							}
						}
					}.show();
				}
				else
				{
					// startSunFlowBuy();
					_toolbutton_backWarrantResult.setVisibility(View.GONE); // by
					// ouyangzhihui
					// 2011-06-28
					dealWithNewStockCodeComingFromEditor();
				}
				break;
			case -1: // del
				if (tmp.length() > 0)
					_current_stock_code.setText(tmp.subSequence(0,
							tmp.length() - 1));
				_current_stock_code.requestFocus();
				_current_stock_code.setSelection(_current_stock_code
						.getText().toString().length());
				break;
			default:
				_current_stock_code.setText(tmp + number);
				_current_stock_code.requestFocus();
				_current_stock_code.setSelection(_current_stock_code
						.getText().toString().length());
				break;
		}
	}

	private OnClickListener	btnOnClickListener	= new OnClickListener()
										{
											@Override
											public void onClick(
													View v)
											{
												final int number = v
														.getId();
												new Thread()
												{
													Runnable	updateRunnable	= new Runnable()
																		{
																			@Override
																			public void run()
																			{
																				dealwithEnterCode(number);
																			}
																		};

													public void run()
													{
														_messageHandler
																.post(updateRunnable);
													}
												}.start();
											}
										};

	private void initInputBtn()
	{
		if (container_input == null)
			return;
		LinearLayout line1 = (LinearLayout) container_input.getChildAt(0);
		LinearLayout line2 = (LinearLayout) container_input.getChildAt(1);
		LinearLayout line3 = (LinearLayout) container_input.getChildAt(2);
		LinearLayout line4 = (LinearLayout) container_input.getChildAt(3);
		Button btn1 = (Button) line1.findViewById(R.id.btn_one);
		Button btn2 = (Button) line1.findViewById(R.id.btn_two);
		Button btn3 = (Button) line1.findViewById(R.id.btn_three);
		Button btn4 = (Button) line2.findViewById(R.id.btn_four);
		Button btn5 = (Button) line2.findViewById(R.id.btn_five);
		Button btn6 = (Button) line2.findViewById(R.id.btn_six);
		Button btn7 = (Button) line3.findViewById(R.id.btn_seven);
		Button btn8 = (Button) line3.findViewById(R.id.btn_eight);
		Button btn9 = (Button) line3.findViewById(R.id.btn_nine);
		Button btnOK = (Button) line4.findViewById(R.id.btn_ok);
		Button btn0 = (Button) line4.findViewById(R.id.btn_zero);
		Button btnDel = (Button) line4.findViewById(R.id.btn_delete);
		btn1.setId(1);
		btn2.setId(2);
		btn3.setId(3);
		btn4.setId(4);
		btn5.setId(5);
		btn6.setId(6);
		btn7.setId(7);
		btn8.setId(8);
		btn9.setId(9);
		btnOK.setId(10);
		btn0.setId(0);
		btnDel.setId(-1);
		btn1.setOnClickListener(btnOnClickListener);
		btn2.setOnClickListener(btnOnClickListener);
		btn3.setOnClickListener(btnOnClickListener);
		btn4.setOnClickListener(btnOnClickListener);
		btn5.setOnClickListener(btnOnClickListener);
		btn6.setOnClickListener(btnOnClickListener);
		btn7.setOnClickListener(btnOnClickListener);
		btn8.setOnClickListener(btnOnClickListener);
		btn9.setOnClickListener(btnOnClickListener);
		btnOK.setOnClickListener(btnOnClickListener);
		btn0.setOnClickListener(btnOnClickListener);
		btnDel.setOnClickListener(btnOnClickListener);
	}

	private void initInputMethod()
	{
		if (container_input == null)
		{
			container_input = (LinearLayout) ((ViewStub) findViewById(R.id.stub_inputMethod))
					.inflate();
			initInputBtn();
		}
		anim_down = AnimationUtils.loadAnimation(this, R.anim.push_down);

		anim_down.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				container_input.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}

			@Override
			public void onAnimationStart(Animation animation)
			{
				StockGroup.tabHost.getTabWidget().setVisibility(View.GONE);
				if (_iconTip != null)
				{
					_iconTip.setVisibility(View.GONE);
				}
			}
		});

		anim_up = AnimationUtils.loadAnimation(this, R.anim.push_up);

		anim_up.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				container_input.setVisibility(View.GONE);
				StockGroup.tabHost.getTabWidget().setVisibility(
						View.VISIBLE);
				if (_iconTip != null)
				{
					_iconTip.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}

			@Override
			public void onAnimationStart(Animation animation)
			{
			}
		});

		editTextView = (TextView) findViewById(R.id.editTextView);
		editTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (container_input == null)
				{
					container_input = (LinearLayout) ((ViewStub) findViewById(R.id.stub_import))
							.inflate();
					initInputBtn();
				}
				if (container_input.getVisibility() == View.VISIBLE)
				{
					return;
				}
				TDStockLog.d(TAG, "ready to hide tab widget");
				/*
				 * _current_stock_code.setFocusable(true);
				 * _current_stock_code.setFocusableInTouchMode(true);
				 */

				lastStockCode = _current_stock_code.getText().toString();

				_current_stock_code.setText("");
				_current_stock_code.requestFocus();
				container_input.startAnimation(anim_down);
				TDStockLog.d(TAG, "ready to show soft-keyboard!");
			}
		});
	}

	private static String	lastStockCode					= "1";
	// ////////////////////////by ouyangzhihui
	// 2011-7-8//////////////////////////////////
	private OnClickListener	onTouchInputMethodOnClickListener	= new OnClickListener()
													{
														@Override
														public void onClick(
																View v)
														{
															if (container_input != null)
															{
																if (container_input
																		.getVisibility() != View.GONE)
																{
																	container_input
																			.startAnimation(anim_up);
																	_current_stock_code
																			.setText(lastStockCode);
																	// _current_stock_code.setSelection(_current_stock_code.getText().toString().length());
																	_current_stock_code
																			.clearFocus();
																}
															}
														}
													};

	@Override
	protected void onCreate(final Bundle savedInstanceState)
	{
		TDStockLog.d(TAG, "create new instance for CurrentStockInfoActivity!");
		super.onCreate(savedInstanceState);
		/* Andy */
		// _context = this;
		// _streamerTimeoutHandler = new StreamerTimeoutHandler(this,
		// _messageHandler);

		// _cdrHelper = new CdrHelper(this, _messageHandler);

		setCurrentStockCode();

		setContentView(R.layout.currentstockinfo);

		// "期指Futures"，"上証SSEI" set Adapter
		initFuturesAndSSEIAdapterType();

		initInputMethod(); // by ouyangzhihui 2011-7-8

		initRes4Replacement();

		_formaterOnSacle2 = DecimalFormat.getInstance();
		_formaterOnSacle2.setMaximumFractionDigits(2);
		_formaterOnSacle2.setMinimumFractionDigits(2);

		_formaterOnSacle1 = DecimalFormat.getInstance();
		_formaterOnSacle1.setMaximumFractionDigits(1);
		_formaterOnSacle1.setMinimumFractionDigits(1);

		// DefaultClickHandler defaultHandler = new DefaultClickHandler(this);

		// _toolbutton_chart = (Button)findViewById(R.id.toolbutton_chart);
		_toolbutton_news = (Button) findViewById(R.id.toolbutton_bullets);
		_toolbutton_wc = (Button) findViewById(R.id.toolbutton_wc);
		_toolbutton_search = (Button) findViewById(R.id.toolbutton_search);

		_toolbutton_addstock = (Button) findViewById(R.id.toolbutton_addstock);

		// _toolbutton_chart.setFocusable(true);
		// _toolbutton_chart.setClickable(true);
		_toolbutton_news.setFocusable(true);
		_toolbutton_news.setClickable(true);
		_toolbutton_wc.setFocusable(true);
		_toolbutton_wc.setClickable(true);

		// _toolbutton_chart.setOnClickListener(defaultHandler);
		_toolbutton_news.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				/*
				 * String stockCode = _current_stock_code.getText().toString();
				 * CurrentStockNewsListActivity._stockCode = stockCode;
				 * CurrentStockNewsListActivity._isComeFromBack = false; //
				 * CurrentStockNewsListActivity
				 * .show(CurrentStockInfoActivity.this, // stockCode); Intent
				 * intent = new Intent(getApplicationContext(),
				 * CurrentStockNewsListActivity.class);
				 * intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
				 * Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				 * 
				 * SwitchForwardActivity(CurrentStockNewsListActivity.class,
				 * intent);
				 */

				// modified by haibo in 2012-02-03 for new version
				String stockCode = _current_stock_code.getText().toString();
				NewStockNewsActivity._stockCode = stockCode;
				Intent intent = new Intent(getApplicationContext(),
						NewStockNewsActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

				SwitchForwardActivity(NewStockNewsActivity.class, intent);

			}

		});
		// _toolbutton_wc.setOnClickListener(defaultHandler);
		_toolbutton_wc.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				WarrantCBBCActivity.currStockCode = ((ITDLApplication) getApplicationContext())
						.getCurrentStockCode();
				WarrantCBBCActivity.currStockName = ((ITDLApplication) getApplicationContext())
						.getCurrentStockName();
				Intent intent = new Intent(getApplicationContext(),
						WarrantCBBCActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				// View view =
				// StockGroup.group.getLocalActivityManager().startActivity(WarrantCBBCActivity.class.getSimpleName(),
				// intent).getDecorView();
				// StockGroup.group.setContentView(view); //modified by haibo,
				// 2011-05-16

				SwitchForwardActivity(WarrantCBBCActivity.class, intent);
			}

		});

		_toolbutton_search.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(getApplicationContext(),
						StockSearchActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				/*
				 * View view =
				 * StockGroup.group.getLocalActivityManager().startActivity
				 * (StockSearchActivity.class.getSimpleName(),
				 * intent).getDecorView();
				 * StockGroup.group.setContentView(view);
				 */
				SwitchForwardActivity(StockSearchActivity.class, intent);
			}
		});

		_toolbutton_addstock
				.setOnClickListener(new AddStockClickHandler(this));

		// modified by ouyangzhihui, 2011-06-09
		_toolbutton_backWarrantResult = (Button) findViewById(R.id.toolbutton_backWarrantResult);
		_toolbutton_backWarrantResult
				.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						SearchWarrantActivity.isFromActivityStockInfo = true;
						Intent intent = new Intent(
								getApplicationContext(),
								SearchWarrantActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
								| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
						// View currView =
						// StockGroup.group.getLocalActivityManager().startActivity(SearchWarrantActivity.class.getSimpleName(),
						// intent).getDecorView();
						// StockGroup.group.setContentView(currView); //modified
						// by
						// ouyangzhihui, 2011-06-09
						SwitchForwardActivity(
								SearchWarrantActivity.class, intent);
					}
				});

		findViewById(R.id.toolbutton_stockstar).setOnClickListener(
				new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						String userName = ((ITDLApplication) getApplicationContext())
								.getUserName("");
						CommonDefn.ModeType iModeType = ((ITDLApplication) getApplicationContext())
								.getModeType();
						if (CommonDefn.ModeType.DELARY == iModeType
								&& CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY
										.equals(userName))
						{
							new CustomizeDialog(
									getMyOwnContext(),
									getResources().getString(
											R.string.info),
									getResources()
											.getString(
													R.string.realtime_info_msg),
									getResources().getString(
											R.string.ok)).show();
							return;
						}

						if (MoreGroup.group == null)
						{
							MoreGroup.forceToGoToRelatingTab();
						}
						StockStarIndexActivity.iFromClass = CurrentStockInfoActivity.class;
						SwitchTabHostActivity(
								4,
								MoreGroup.GetActivityGroupHostControl(),
								StockStarIndexActivity.class);
					}
				});

		// by zhengan
		// Button _toolbutton_soccer = (Button)
		// findViewById(R.id.toolbutton_soccer);// 足球
		// Button _toolbutton_horserace = (Button)
		// findViewById(R.id.toolbutton_horserace);// 赛马
		//
		// _toolbutton_soccer.setOnClickListener(
		// new View.OnClickListener()
		// {
		// @Override
		// public void onClick(View v)
		// {
		// forwardToSoccerActivity();
		// }
		// });
		//
		// _toolbutton_horserace.setOnClickListener(
		// new View.OnClickListener()
		// {
		// @Override
		// public void onClick(View v)
		// {
		// forwardToHorseraceActivity();
		// }
		// });

		_stkTimeView = (StkTimeView) ((ViewGroup) findViewById(R.id.chart_container))
				.getChildAt(0);
		if (_stkTimeView == null)
		{
			TDStockLog.e(TAG, "can't find _stkTimeView!");
		}

		_chart_mask = (TextView) findViewById(R.id.chart_mask);

		_chart_mask.setOnClickListener(new ChartClickHandler(this));

		_index_hsi = (TextView) findViewById(R.id.index_hsi_value);
		_index_his_net = (TextView) findViewById(R.id.index_hsi_net);
		_index_his_turnover = (TextView) findViewById(R.id.index_hsi_turn_over);

		_index_phsi = (TextView) findViewById(R.id.index_hscei_value);
		_index_phsi_net = (TextView) findViewById(R.id.index_hscei_net);

		_index_futures_hsi_1 = (TextView) findViewById(R.id.index_futures_hsi_1_value);
		_index_futures_hsi_1_net = (TextView) findViewById(R.id.index_futures_hsi_1_net);

		_index_futures_hsi_2 = (TextView) findViewById(R.id.index_futures_hsi_2_value);
		_index_futures_hsi_2_net = (TextView) findViewById(R.id.index_futures_hsi_2_net);

		_worldindex_sse1 = (TextView) findViewById(R.id.worldindex_sse1_value);
		_worldindex_sse1_net = (TextView) findViewById(R.id.worldindex_sse1_net);

		_server_time = (TextView) findViewById(R.id.server_timestamp);

		resetSyncServerTimeForDelayMode();

		// _current_stock_code =
		// (TextView)findViewById(R.id.current_stock_code);
		_current_stock_code = (EditText) findViewById(R.id.current_stock_code);
		_current_stock_code.setText(_stockCode);

		_current_stock_code.setClickable(true);
		_current_stock_code.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				_current_stock_code.setText(""); // clear the text when ready to
				// edit it
			}

		});

		_current_stock_code.setOnTouchListener(new OnTouchListener()
		{

			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				v.setTag(1);
				return false;
			}

		});

		_current_stock_code
				.setOnFocusChangeListener(new OnFocusChangeListener()
				{

					@Override
					public void onFocusChange(View v, boolean hasFocus)
					{
						if (hasFocus && v.getTag() != null
								&& v.getTag().equals(1))
						{
							_current_stock_code.setText(""); // clear the text
														// when
							// ready to edit it
						}
						else
						{
							v.setTag(-1);
						}
					}

				});

		// Andy Testing
		// Mark to get the event done
		_current_stock_code.setImeOptions(EditorInfo.IME_ACTION_DONE);
		_current_stock_code
				.setOnEditorActionListener(new TextView.OnEditorActionListener()
				{
					@Override
					public boolean onEditorAction(TextView v,
							int actionId, KeyEvent event)
					{
						if (actionId == EditorInfo.IME_ACTION_DONE)
						{
							// Close Keybaord
							Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							InputMethodManager imm = (InputMethodManager) service;
							imm.hideSoftInputFromWindow(
									_current_stock_code
											.getWindowToken(), 0);
							_current_stock_code.clearFocus();

							// If there is no network, create a prompt
							if (!SystemInfo
									.isNetworkingConnected(CurrentStockInfoActivity.this))
								new CustomizeDialog(
										CurrentStockInfoActivity.this
												.getMyOwnContext(),
										getResources().getString(
												R.string.info),
										getResources()
												.getString(
														R.string.networking_disconnect_tips))
										.show();
							else
							{
								_toolbutton_backWarrantResult
										.setVisibility(View.GONE); // by
								// ouyangzhihui
								// 2011-06-28
								dealWithNewStockCodeComingFromEditor();
							}
							return true;
						}
						return false;
					}
				});

		_current_stock_chinese_short_name = (TextView) findViewById(R.id.current_stock_chinese_name);
		_current_stock_nominal = (TextView) findViewById(R.id.current_stock_nominal);

		_up_down = (ImageView) findViewById(R.id.current_stock_up_down_img);
		_current_stock_net = (TextView) findViewById(R.id.current_stock_net);
		_current_stock_net_percentage = (TextView) findViewById(R.id.current_stock_net_percentage);

		_current_stock_sharetraded = (TextView) findViewById(R.id.current_stock_sharetraded);
		_current_stock_turnover = (TextView) findViewById(R.id.current_stock_turnover);
		_current_stock_prevcloseprice = (TextView) findViewById(R.id.current_stock_prevcloseprice);
		_current_stock_openprice = (TextView) findViewById(R.id.current_stock_openprice);
		_current_stock_highprice = (TextView) findViewById(R.id.current_stock_highprice);
		_current_stock_lowprice = (TextView) findViewById(R.id.current_stock_lowprice);

		_current_stock_bidprice = (TextView) findViewById(R.id.current_stock_bidprice);
		_current_stock_askprice = (TextView) findViewById(R.id.current_stock_askprice);

		// add SunFlower Animation.
		_buy_waiting = (LinearLayout) findViewById(R.id.buy_waiting);
		sunFlowerView1 = new SunFlowerView(this);

		_current_stock_bid_share_1 = (TextView) findViewById(R.id.current_stock_bid_share_1);
		_current_stock_bid_share_2 = (TextView) findViewById(R.id.current_stock_bid_share_2);
		_current_stock_bid_share_3 = (TextView) findViewById(R.id.current_stock_bid_share_3);
		_current_stock_bid_share_4 = (TextView) findViewById(R.id.current_stock_bid_share_4);
		_current_stock_bid_share_5 = (TextView) findViewById(R.id.current_stock_bid_share_5);

		_current_stock_bid_queue_1 = (TextView) findViewById(R.id.current_stock_bid_queue_1);
		_current_stock_bid_queue_2 = (TextView) findViewById(R.id.current_stock_bid_queue_2);
		_current_stock_bid_queue_3 = (TextView) findViewById(R.id.current_stock_bid_queue_3);
		_current_stock_bid_queue_4 = (TextView) findViewById(R.id.current_stock_bid_queue_4);
		_current_stock_bid_queue_5 = (TextView) findViewById(R.id.current_stock_bid_queue_5);

		_current_stock_ask_share_1 = (TextView) findViewById(R.id.current_stock_ask_share_1);
		_current_stock_ask_share_2 = (TextView) findViewById(R.id.current_stock_ask_share_2);
		_current_stock_ask_share_3 = (TextView) findViewById(R.id.current_stock_ask_share_3);
		_current_stock_ask_share_4 = (TextView) findViewById(R.id.current_stock_ask_share_4);
		_current_stock_ask_share_5 = (TextView) findViewById(R.id.current_stock_ask_share_5);

		_current_stock_ask_queue_1 = (TextView) findViewById(R.id.current_stock_ask_queue_1);
		_current_stock_ask_queue_2 = (TextView) findViewById(R.id.current_stock_ask_queue_2);
		_current_stock_ask_queue_3 = (TextView) findViewById(R.id.current_stock_ask_queue_3);
		_current_stock_ask_queue_4 = (TextView) findViewById(R.id.current_stock_ask_queue_4);
		_current_stock_ask_queue_5 = (TextView) findViewById(R.id.current_stock_ask_queue_5);

		_rowForWarrant = (TableRow) findViewById(R.id.for_warrant_row);

		_current_stock_lotsize = (TextView) findViewById(R.id.current_stock_lotsize);
		_current_stock_ex_ymd = (TextView) findViewById(R.id.current_stock_ex_ymd);
		_current_stock_year_high = (TextView) findViewById(R.id.current_stock_year_high);
		_current_stock_div_ymd = (TextView) findViewById(R.id.current_stock_div_ymd);

		_current_stock_year_low = (TextView) findViewById(R.id.current_stock_year_low);
		_current_stock_div_value = (TextView) findViewById(R.id.current_stock_div_value);
		_current_stock_profitpershare = (TextView) findViewById(R.id.current_stock_profitpershare);
		_current_stock_rate_of_return = (TextView) findViewById(R.id.current_stock_rate_of_return);

		_current_stock_pe = (TextView) findViewById(R.id.current_stock_pe);
		_current_stock_currency = (TextView) findViewById(R.id.current_stock_currency);
		_current_stock_day_10_avg = (TextView) findViewById(R.id.current_stock_day_10_avg);

		_current_stock_rsi9 = (TextView) findViewById(R.id.current_stock_rsi9);
		_current_stock_day_20_avg = (TextView) findViewById(R.id.current_stock_day_20_avg);
		_current_stock_rsi14 = (TextView) findViewById(R.id.current_stock_rsi14);
		_current_stock_day_50_avg = (TextView) findViewById(R.id.current_stock_day_50_avg);

		{
			_current_stock_day_100_avg = (TextView) findViewById(R.id.current_stock_day_100_avg);
			_current_stock_day_200_avg = (TextView) findViewById(R.id.current_stock_day_200_avg);
			_current_stock_day_250_avg = (TextView) findViewById(R.id.current_stock_day_250_avg);
		}

		_broker_bid_queue_spread_left = (LinearLayout) findViewById(R.id.broker_bid_queue_spread_left);
		_broker_bid_queue_spread_right = (LinearLayout) findViewById(R.id.broker_bid_queue_spread_right);

		_broker_ask_queue_spread_left = (LinearLayout) findViewById(R.id.broker_ask_queue_spread_left);
		_broker_ask_queue_spread_right = (LinearLayout) findViewById(R.id.broker_ask_queue_spread_right);

		_broker_bid_queue_spread_left_ch = (LinearLayout) findViewById(R.id.broker_bid_queue_spread_left_ch);
		_broker_bid_queue_spread_right_ch = (LinearLayout) findViewById(R.id.broker_bid_queue_spread_right_ch);

		_broker_ask_queue_spread_left_ch = (LinearLayout) findViewById(R.id.broker_ask_queue_spread_left_ch);
		_broker_ask_queue_spread_right_ch = (LinearLayout) findViewById(R.id.broker_ask_queue_spread_right_ch);

		// _toolbutton =(ViewGroup) findViewById(R.id.toolbutton);

		_mContainer = (ViewGroup) findViewById(R.id.container);
		_broker_queue_name = (LinearLayout) findViewById(R.id.broker_queue_name);
		_broker_queue_code = (LinearLayout) findViewById(R.id.broker_queue_code);

		// Prepare the broker queue
		_broker_queue_name.setClickable(true);
		_broker_queue_name.setFocusable(true);
		_broker_queue_name.setOnClickListener(this);

		_broker_queue_code.setClickable(true);
		_broker_queue_code.setFocusable(true);
		_broker_queue_code.setOnClickListener(this);

		// Since we are caching large views, we want to keep their cache
		// between each animation
		_mContainer
				.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

		initTradetickerView();
		init_broker_view();

		// modify by zor(ouyangzhihui) -start
		_img_logo = (ImageView) findViewById(R.id.img_logo);
		_img_logo.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent it = new Intent(CurrentStockInfoActivity.this,
						AboutActivity.class);
				it.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				startActivityForResult(it, Activity.RESULT_OK);
			}
		});
		// modify by zor(ouyangzhihui) -start
		_scrollview = (ScrollView) findViewById(R.id.scrollview01);
		_scrollview.setScrollbarFadingEnabled(true);
		// 处理软键盘
		_scrollview.setOnClickListener(onTouchInputMethodOnClickListener);
		ViewGroup viewGroup_container = (ViewGroup) _scrollview.getChildAt(0);
		for (int i = 0; i < viewGroup_container.getChildCount(); i++)
		{
			viewGroup_container.getChildAt(i).setOnClickListener(
					onTouchInputMethodOnClickListener);
		}

		/* resetQueueForDelayMode(); */

		resetBrokerQueueForDelayMode();

		resetStockTradetickerForDelayMode();

		resetMarketDepthForDelayMode();

		/* Andy */
		// new RePostCdrTask().execute();

		// setAdShowCondition();

		_current_stock_bid = (ViewGroup) findViewById(R.id.current_stock_bid);

		initResources();

		initBtnEntryForDelayMode();

		// Set up link for the Trading App
		setlinkToTrading();

		WebViewHelper.showAd(this, (WebView) findViewById(R.id.webView));

		isChangeModeType = false;
	}

	public static boolean	isChangeModeType		= false;
	/*-----------------by ouyangzhihui 2011-08-24-------------------*/
	protected static String	_indexFuturesAdapter	= IndexFuturesInfo.ADAPTER;
	protected static String	_indexSSEIAdapter		= WorldIndexDelayInfo.ADAPTER;

	private void initFuturesAndSSEIAdapterType()
	{
		/*----"期指Futures","上証SSEI"， delay - label add "*"-- by ouyangzhihui 2011-08-26---*/
		if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN
				&& !((ITDLApplication) getApplicationContext())
						.getIsRealtimeFutures())
		{
			TextView index_futures_label = (TextView) findViewById(R.id.index_futures_label);
			TextView next_month_label = (TextView) findViewById(R.id.next_month_label);
			index_futures_label.setText(index_futures_label.getText()
					.toString() + "*");
			next_month_label.setText(next_month_label.getText().toString()
					+ "*");
		}
		if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN
				&& !((ITDLApplication) getApplicationContext())
						.getIsRealtimeSSEI())
		{
			TextView index_sse1_label = (TextView) findViewById(R.id.index_sse1_label);
			index_sse1_label.setText(index_sse1_label.getText().toString()
					+ "*");
		}
		/*----"期指Futures","上証SSEI"， delay - label add "*"-- by ouyangzhihui 2011-08-26---*/

		/* "期指"2 (account login && svcPlan=1) || activeCode login */
		if ((((ITDLApplication) getApplicationContext())
				.getIsRealtimeFutures() && ((ITDLApplication) getApplicationContext())
				.getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN)
				|| ((ITDLApplication) getApplicationContext())
						.getModeType() == CommonDefn.ModeType.ACTIVECODE)
		{
			// 實時數據
			_indexFuturesAdapter = IndexFuturesInfo.adapter_realtime;
		}
		else
		{
			_indexFuturesAdapter = IndexFuturesInfo.adapter_delay;
		}

		/* "上証"5 (account login && svcPlan=1) || activeCode login */
		if ((((ITDLApplication) getApplicationContext()).getIsRealtimeSSEI() && ((ITDLApplication) getApplicationContext())
				.getModeType() == CommonDefn.ModeType.ACCOUNTLOGIN)
				|| ((ITDLApplication) getApplicationContext())
						.getModeType() == CommonDefn.ModeType.ACTIVECODE)
		{
			// 實時數據
			_indexSSEIAdapter = WorldIndexInfo.ADAPTER;
		}
		else
		{
			_indexSSEIAdapter = WorldIndexDelayInfo.ADAPTER;
		}
	}

	/*-----------------by ouyangzhihui 2011-08-24-------------------*/

	private LinearLayout	_tool_bottom;
	private Button			_btn_realtime_entry;
	private Button			_btn_login_entry;
	private Button			_btn_customer_entry;

	private void initBtnEntryForDelayMode()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			_tool_bottom = (LinearLayout) findViewById(R.id._tool_bottom);
			_btn_realtime_entry = (Button) findViewById(R.id.btn_realtime_entry);
			_btn_login_entry = (Button) findViewById(R.id.btn_login_entry);
			_btn_customer_entry = (Button) findViewById(R.id.btn_customer_entry);

			_tool_bottom.setVisibility(View.VISIBLE);

			_btn_realtime_entry.setId(1);
			_btn_login_entry.setId(2);
			_btn_customer_entry.setId(3);

			_btn_realtime_entry.setOnClickListener(btnEntryOnClickListener);
			_btn_login_entry.setOnClickListener(btnEntryOnClickListener);
			_btn_customer_entry.setOnClickListener(btnEntryOnClickListener);
		}
	}

	// execute the method just once
	private void restoreToRealTimeModeIfNeed()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Realtime
				&& ((ITDLApplication) getApplicationContext())
						.isReadyToChangeMode())
		{
			((ITDLApplication) getApplicationContext())
					.setReadyToChangeMode(false);
			// ----------------resetSyncServerTimeForDelayMode();----------------
			_server_time.setTextColor(Color.WHITE);
			_server_time.setText("");
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _server_time.postInvalidate();
			// ----------------resetSyncServerTimeForDelayMode();----------------

			// ----------------resetBrokerQueueForDelayMode()---------------
			{
				TextView queue = (TextView) findViewById(R.id.txt_broker_queue_code);
				queue.setText("");
				queue.setVisibility(View.GONE);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. queue.postInvalidate();
			}
			// ----------------resetBrokerQueueForDelayMode()---------------

			// ----------------resetStockTradetickerForDelayMode()---------------
			{
				TextView queue = (TextView) findViewById(R.id.txt_stock_tradeticker);
				queue.setText("");
				queue.setVisibility(View.GONE);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. queue.postInvalidate();
			}
			// ----------------resetStockTradetickerForDelayMode()---------------

			// ----------------resetMarketDepthForDelayMode()----------------
			{
				TextView queue = (TextView) findViewById(R.id.txt_market_depth);
				queue.setText(Html.fromHtml(""));
				queue.setVisibility(View.GONE);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. queue.postInvalidate();

				if (_current_stock_ask_queue_1 != null)
				{
					_current_stock_ask_queue_1.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_ask_queue_1.postInvalidate();
				}
				if (_current_stock_ask_queue_2 != null)
				{
					_current_stock_ask_queue_2.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_ask_queue_2.postInvalidate();
				}
				if (_current_stock_ask_queue_3 != null)
				{
					_current_stock_ask_queue_3.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_ask_queue_3.postInvalidate();
				}
				if (_current_stock_ask_queue_4 != null)
				{
					_current_stock_ask_queue_4.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_ask_queue_4.postInvalidate();
				}
				if (_current_stock_ask_queue_5 != null)
				{
					_current_stock_ask_queue_5.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_ask_queue_5.postInvalidate();
				}
			}

			// ----------------resetMarketDepthForDelayMode()----------------

			// ----------------initBtnEntryForDelayMode()---------------
			_tool_bottom = (LinearLayout) findViewById(R.id._tool_bottom);
			_tool_bottom.setVisibility(View.GONE);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _tool_bottom.postInvalidate();
			// ----------------initBtnEntryForDelayMode()---------------
			// initBtnEntryForDelayMode();

		}
	}

	private OnClickListener	btnEntryOnClickListener	= new OnClickListener()
											{
												@Override
												public void onClick(
														View v)
												{
													int id = v.getId();
													Class<? extends Activity> cls = null;
													switch (id)
													{
														case 1:
															// new TrialQuery().execute();
															TrialQueryAuth();
															break;
														case 2:
															RealtimeStockActivity.IsCustomerForwardToAccountLogin = true;
															cls = AccountLoginActivity.class;
															break;
														case 3:
															cls = RegisterActivity.class;
															break;
													}

													if (cls != null)
													{
														Intent intent = new Intent(
																getApplicationContext(),
																cls);
														intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);

														SwitchActivityFromHost(
																cls,
																intent);
													}
												}
											};

	/**
	 * 驗證碼登錄驗證
	 * 
	 * @author ouyangzhihui
	 */
	private void TrialQueryAuth()
	{
		appHost.LS_RequestFreeTrialVerifiy(new ITDStockReqFreeVerify_Result()
		{
			@Override
			public void TDStockReqFreeVerify_Response(
					TDStockReqFreeVerify_Result iResult)
			{
				Class<? extends Activity> _cls = null;

				TDStockLog.d(TAG, "trial query: " + iResult.statusCode
						+ "-" + iResult.errorMessage);

				if (iResult.statusCode.equals("0"))
				{
					// 如果用驗證碼登錄過，則直接自動登錄
					_prefs = getSharedPreferences(
							CommonDefn.SYSTEM_CURRENT_SETTING,
							Context.MODE_PRIVATE);
					boolean isSendActiveCode = _prefs.getBoolean(
							CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE,
							false);
					String trial_active_code = _prefs.getString(
							CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, "");

					TDStockLog.d(TAG, "test isSendActiveCode="
							+ isSendActiveCode
							+ " , test trial_active_code="
							+ trial_active_code);
					if (/* isSendActiveCode && */!""
							.equals(trial_active_code))
					{
						VerifyActiveCodeActivity.activeCode = trial_active_code; // 自動登錄
					}
					_cls = VerifyActiveCodeActivity.class; // 登錄界面輸入驗證碼
				}
				else if (iResult.statusCode.equals("1")) // 對不起！機身編號未登記過免費試用。
				{
					_cls = DeclareTrialActivity.class;
				}
				else if (iResult.statusCode.equals("2")) // 機身編號試用已過期
				{
					new CustomizeDialog(CurrentStockInfoActivity.this
							.getMyOwnContext(), getResources()
							.getString(R.string.info),
							"試用已完結，如想繼續使用，請按新客戶登記。", getResources()
									.getString(R.string.ok)).show();
					return;
				}
				else if (iResult.statusCode.equals("3")) //
				{
					_cls = VerifyActiveCodeActivity.class; // 已经登记过试用，但未使用验证码登录过(登錄界面輸入驗證碼)
				}
				else
				{
					new CustomizeDialog(
							getMyOwnContext(),
							getResources().getString(R.string.info),
							iResult.errorMessage.length() >= 1 ? iResult.errorMessage
									: "系統錯誤，請稍後再試，不便之處敬請原諒",
							getResources().getString(R.string.ok))
							.show();
					return;
				}

				if (_cls != null)
				{
					Intent intent = new Intent(getApplicationContext(),
							_cls);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
					SwitchActivityFromHost(_cls, intent);
				}
			}
		});
	}

	/**
	 * 驗證碼登錄驗證
	 * 
	 * @author ouyangzhihui
	 */
	// private class TrialQuery extends AsyncTask<String, Void, Void>
	// {
	// // ProgressDialog _dialog;
	// Class<? extends Activity> _cls = null;
	// String[] auth_info;
	//
	// @Override
	// protected Void doInBackground(String... params)
	// {
	// String deviceId = _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
	// if (deviceId.trim().length() < 2)
	// deviceId = SystemInfo.getDeviceId(CurrentStockInfoActivity.this);
	// TrialAccountAuth auth = new TrialAccountAuth(deviceId);
	// auth_info = auth.getAuthentication();
	// return null;
	// }
	//
	// @Override
	// protected void onCancelled()
	// {
	// super.onCancelled();
	// /*
	// * if(_dialog != null) _dialog.dismiss();
	// */
	// }
	//
	// @Override
	// protected void onPostExecute(Void result)
	// {
	// super.onPostExecute(result);
	// /*
	// * if(_dialog != null) _dialog.dismiss();
	// */
	//
	// TDStockLog.d(TAG, "auth_info[0]=" + auth_info[0]);
	// TDStockLog.d(TAG, "auth_info[1]=" + auth_info[1]);
	// if (auth_info[0].equals("0"))
	// {
	// // 如果用驗證碼登錄過，則之間自動登錄
	// _prefs = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING,
	// Context.MODE_PRIVATE);
	// boolean isSendActiveCode =
	// _prefs.getBoolean(CommonDefn.PREFERENCE_IS_SEND_ACTIVE_CODE, false);
	// String trial_active_code =
	// _prefs.getString(CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, "");
	//
	// TDStockLog.d(TAG, "test isSendActiveCode=" + isSendActiveCode +
	// " , test trial_active_code=" + trial_active_code);
	// if (/*isSendActiveCode && */!"".equals(trial_active_code))
	// {
	// VerifyActiveCodeActivity.activeCode = trial_active_code; // 自動登錄
	// }
	// _cls = VerifyActiveCodeActivity.class; // 登錄界面輸入驗證碼
	// }
	// else if (auth_info[0].equals("1")) // 對不起！機身編號未登記過免費試用。
	// {
	// _cls = DeclareTrialActivity.class;
	// }
	// else if (auth_info[0].equals("2")) // 機身編號試用已過期
	// {
	// // _cls = DeclareTrialActivity.class;
	// new CustomizeDialog(CurrentStockInfoActivity.this.getMyOwnContext(),
	// getResources().getString(R.string.info), "試用已完結，如想繼續使用，請按新客戶登記。",
	// getResources().getString(R.string.ok)).show();
	// return;
	// }
	// else if (auth_info[0].equals("3")) //
	// {
	// _cls = VerifyActiveCodeActivity.class; // 已经登记过试用，但未使用验证码登录过(登錄界面輸入驗證碼)
	// }
	// else
	// {
	// new CustomizeDialog(getMyOwnContext(),
	// getResources().getString(R.string.info), auth_info[1].length() >= 1 ?
	// auth_info[1] : "系統錯誤，請稍後再試，不便之處敬請原諒", getResources()
	// .getString(R.string.ok)).show();
	// return;
	// }
	//
	// if (_cls != null)
	// {
	// Intent intent = new Intent(getApplicationContext(), _cls);
	// intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
	// // startActivity(intent);
	// SwitchActivityFromHost(_cls, intent);
	// }
	// }
	//
	// @Override
	// protected void onPreExecute()
	// {
	// super.onPreExecute();
	// /*
	// * _dialog = new ProgressDialog(CurrentStockInfoActivity.this,
	// * Html.fromHtml("正在初始化數據並連接至伺服器<br/>請稍候...").toString());
	// * _dialog.show();
	// */
	// }
	// }

	private void setCurrentStockCode()
	{
		_prefsStockCode = getSharedPreferences(
				CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		String stockCode = "1";
		if (_prefsStockCode != null)
		{
			stockCode = _prefsStockCode.getString(
					CommonDefn.PREFERENCE_STOCK_CODE, "1");
			if ("".equals(stockCode))
				stockCode = "1"; // modify by ouyangzhihui 2011-06-01
			if (TextUtils.isDigitsOnly(stockCode))
			{
				stockCode = Integer.toString(Integer
						.parseInt(stockCode, 10));
			}
			else
			{
				stockCode = "1";
			}
			_stockCode = stockCode;
			((ITDLApplication) this.getApplication())
					.setCurrentStockCode(_stockCode);
			TDStockLog.d(TAG, "ready to draw chart");
		}
	}

	private void initResources()
	{
		_securities_company_code = getResources().getString(
				R.string.stock_company_code).split("[,]");
		_securities_company_name = getResources().getString(
				R.string.stock_company_name);
	}

	// start Add SunFlower.
	private void startSunflower()
	{
		TDStockLog.d(TAG, "startSunFlower----start");

		final Runnable startAnim = new Runnable()
		{
			public void run()
			{

				if (_buy_waiting != null && sunFlowerView1 != null)
				{
					TDStockLog.d(TAG, "startSunFlower----success");
					synchronized (sunFlowerView1)
					{
						_buy_waiting.removeAllViews();
						_buy_waiting.addView(sunFlowerView1);
						sunFlowerView1.startAnimation();
					}
				}

			}
		};

		if (_messageHandler != null)
		{

			new Thread()
			{
				public void run()
				{
					_messageHandler.post(startAnim);
				}
			}.start();

		}
	}

	// stop and remove SunFlower.
	private void stopSunflower()
	{
		TDStockLog.d(TAG, "stopSunFlower----stop");
		if (_buy_waiting != null && sunFlowerView1 != null)
		{
			TDStockLog.d(TAG, "stopSunFlower----success");

			final Runnable stopAnim = new Runnable()
			{
				public void run()
				{

					synchronized (sunFlowerView1)
					{
						sunFlowerView1.stopAnimation();
						_buy_waiting.removeAllViews();
					}

				}
			};

			if (_messageHandler != null)
			{

				new Thread()
				{
					public void run()
					{
						_messageHandler.post(stopAnim);
					}
				}.start();

			}

		}
	}

	/*
	 * private void setAdShowCondition() { TDStockLog.d(TAG,
	 * "CDRTESTING>>setAdShowCondition1>" + _hasSubscribedItems);
	 * _hasSubscribedItems = false; DBHelper dbHelper = new DBHelper(this); try
	 * { List<String[]> items = null; int customerId = -1;
	 * 
	 * customerId = ((ITDLApplication) getApplicationContext()).getUserId(-1);
	 * items = dbHelper.getSubscribeItemsByUserId(customerId);
	 * _hasSubscribedItems = (items != null && items.size() >= 1);
	 * TDStockLog.d(TAG, "CDRTESTING>>setAdShowCondition2>" +
	 * _hasSubscribedItems); } catch (Exception e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); } finally { dbHelper.cleanup(); } }
	 */

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		TDStockLog.d("state", "Paused");
		super.onPause();

		_scrollview.performClick(); // 处理软键盘

		// unRegisterAppExitReceiver();

		/*
		 * if(_stkTimeView != null) {
		 * if(_stkTimeView._itemCodeChangeListenerReceiver != null) { try {
		 * this.
		 * unregisterReceiver(_stkTimeView._itemCodeChangeListenerReceiver); }
		 * catch(Exception e) { Log.e(TAG,
		 * "failed to unregisterReceiver:  _itemCodeChangeListenerReceiver! ");
		 * } } } else { Log.e(TAG, "_stkTimeView = null! "); }
		 */
		((ITDLApplication) CurrentStockInfoActivity.this.getApplication())
				.setTimeChartInBackground(true);

		/* Andy */
		// if (_streamerTimeoutHandler != null)
		// {
		// _streamerTimeoutHandler.resetCounter();
		// }

		/*
		 * if (_cdrHelper != null) { _cdrHelper._isPause = true;
		 * //((ITDLApplication) getApplicationContext()).setCdrSender(this);
		 * _cdrHelper.saveCdrCounter(false); }
		 */

		{
			/* Andy */
			// ((ITDLApplication) getApplicationContext()).setResetCDR(true);

			/*
			 * if(_subscrRefs == null || _subscrRefs.isEmpty()) { return; }
			 */
			/*
			 * try { _myClient =
			 * ((ITDLApplication)getApplicationContext()).getLightStreamerClient
			 * (); if(_subscrRefs != null && !_subscrRefs.isEmpty()) {
			 * SubscribedTableKey[] subscrKeys = new
			 * SubscribedTableKey[_subscrRefs.size()]; int index = 0;
			 * for(SubscribedTableKey value: _subscrRefs) { subscrKeys[index++]
			 * = value; } //SubscribedTableKey[] subscrKeys =
			 * (SubscribedTableKey[]) _subscrRefs.toArray(new
			 * SubscribedTableKey[0]); _myClient.unsubscribeTables(subscrKeys);
			 * } Log.d(TAG, "unsubscribeTables all items!"); if(_subscrRefs !=
			 * null && !_subscrRefs.isEmpty()) { _subscrRefs.clear(); } //
			 * _isSubscribed = false; } catch(Exception e) { Log.d(TAG,
			 * "unsubscribe exception happened!" + ( e.getMessage() == null ? ""
			 * : e.getMessage())); e.printStackTrace(); }
			 */

			// unSubscribeAllItems(); //modified by haibo, 2011-06-14, to avoid
			// anr

		}

	}

	@Override
	protected void onResume()
	{
		if (isChangeModeType)
		{
			// "期指Futures"，"上証SSEI" set Adapter
			initFuturesAndSSEIAdapterType();
			isChangeModeType = false;
		}

		LS_Authentication_Result IntLoginResult = null;
		Runnable disclaimerCall = null;

		// Show a disclaimer window
		_prefsStockCode = getSharedPreferences(
				CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		if (_prefsStockCode != null)
		{
			String isFristLoginApp = _prefsStockCode.getString(
					CommonDefn.PREFERENCE_IS_FIRST_LOGON_APP, "true");
			if ("true".equals(isFristLoginApp) || "".equals(isFristLoginApp))
			{
				IntLoginResult = new LS_Authentication_Result(loginResult);
				disclaimerCall = new Runnable()
				{
					public void run()
					{
						Intent intent = new Intent(getMyOwnContext(),
								DisclaimersActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
						startActivityForResult(intent, 0);
					}
				};
			}
		}

		// ((ITDLApplication) getApplicationContext()).setCdrSender(this);
		super.onResume();
		TDStockLog.d("state", "Resume");

		// by ouyangzhihui 2011-06-15
		_toolbutton_backWarrantResult
				.setVisibility(SearchWarrantActivity.isNextActivityStockInfo ? View.VISIBLE
						: View.GONE);
		SearchWarrantActivity.isNextActivityStockInfo = false;

		((ITDLApplication) CurrentStockInfoActivity.this.getApplication())
				.setTimeChartInBackground(false);

		restoreToRealTimeModeIfNeed();

		// connectLightStreamerEx();

		/*
		 * if (_cdrHelper != null) { _cdrHelper.startCounter(); }
		 */

		/*
		 * stopSunFlowBuy(); //moved by haibo, 2011-04-26 startSunFlowBuy();
		 * //moved by haibo, 2011-04-26
		 *//*
			 * final Runnable myUpdateResults = new Runnable() { public void
			 * run() { if (((ITDLApplication)
			 * getApplicationContext()).isLightStreamerConnected()) {
			 * onConnectionEstablished(); } else {
			 * connectLightStreamerEx(CurrentStockInfoActivity
			 * .this.getMyOwnContext()); } } }; new Thread() { public void run()
			 * { _messageHandler.post(myUpdateResults); } }.start();
			 */
		if (disclaimerCall != null)
		{
			loginResult = new LS_Authentication_Result(IntLoginResult);
			_messageHandler.postDelayed(disclaimerCall, 200);
		}
	}

	protected void initRes4Replacement()
	{
		_res4ReplaceMent = new String[2][6];
		_res4ReplaceMent[0][0] = getResources().getString(
				R.string.short_name_ex_ymd);
		_res4ReplaceMent[0][1] = getResources().getString(
				R.string.short_name_div_ymd);
		_res4ReplaceMent[0][2] = getResources().getString(
				R.string.short_name_div_value);
		_res4ReplaceMent[0][3] = getResources().getString(
				R.string.short_name_rate_of_return);
		_res4ReplaceMent[0][4] = getResources().getString(
				R.string.short_name_profitpershare);
		_res4ReplaceMent[0][5] = getResources().getString(
				R.string.short_name_pe);

		_res4ReplaceMent[1][0] = getResources().getString(
				R.string.exchange_ratio);
		_res4ReplaceMent[1][1] = getResources().getString(R.string.exp_date);
		_res4ReplaceMent[1][2] = getResources()
				.getString(R.string.exer_price);
		_res4ReplaceMent[1][3] = getResources()
				.getString(R.string.call_price);
		_res4ReplaceMent[1][4] = getResources().getString(R.string.premium);
		_res4ReplaceMent[1][5] = getResources().getString(
				R.string.percent_out);

		_label4ReplaceMent = new TextView[6];

		_label4ReplaceMent[0] = (TextView) findViewById(R.id.replacement_label_01);
		_label4ReplaceMent[1] = (TextView) findViewById(R.id.replacement_label_02);
		_label4ReplaceMent[2] = (TextView) findViewById(R.id.replacement_label_03);
		_label4ReplaceMent[3] = (TextView) findViewById(R.id.replacement_label_04);
		_label4ReplaceMent[4] = (TextView) findViewById(R.id.replacement_label_05);
		_label4ReplaceMent[5] = (TextView) findViewById(R.id.replacement_label_06);

		_field_value_4ReplaceMent = new TextView[6];
		_field_value_4ReplaceMent[0] = (TextView) findViewById(R.id.current_stock_ex_ymd);
		_field_value_4ReplaceMent[1] = (TextView) findViewById(R.id.current_stock_div_ymd);
		_field_value_4ReplaceMent[2] = (TextView) findViewById(R.id.current_stock_div_value);
		_field_value_4ReplaceMent[3] = (TextView) findViewById(R.id.current_stock_rate_of_return);
		_field_value_4ReplaceMent[4] = (TextView) findViewById(R.id.current_stock_profitpershare);
		_field_value_4ReplaceMent[5] = (TextView) findViewById(R.id.current_stock_pe);

		_field_current_stock_call_put = (TextView) findViewById(R.id.current_stock_call_put);
		_field_current_stock_gearing = (TextView) findViewById(R.id.current_stock_gearing);

	}

	// @Override
	// public void onConfigurationChanged(Configuration newConfig)
	// {
	// // super.onConfigurationChanged(newConfig);
	// /*
	// * if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
	// * forwardToNvChart(); }
	// */
	//
	// forwardToChartActivity();
	//
	// super.onConfigurationChanged(newConfig);
	// }

	private void forwardToNvChart()
	{
		/*
		 * new Thread() { public void run() { Intent intent = new
		 * Intent(getApplicationContext(),NvChart.class);
		 * intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		 * intent.putExtra(FinalKey.ITEMCODE, _stockCode);
		 * startActivity(intent); } }.start();
		 */

		// Intent intent = new Intent(getApplicationContext(),NvChart.class);
		Intent intent = new Intent(getApplicationContext(),
				StkChartActivity.class);

		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
				| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(FinalKey.ITEMCODE, _stockCode);

		// startActivityForResult(intent, Activity.RESULT_OK);
		SwitchActivityFromHost(StkChartActivity.class, intent);
		// appHost.actListController.ActivityForwardSwitch(this,
		// StkChartActivity.class, intent);
		// startActivity(intent);
		// this.finish();

	}

	public synchronized void updateIndex(Bundle bundle)
	{
		String index_name = bundle.getString(MESSAGE_KEY_INDEX_NAME);
		String value = bundle.getString(IndexInfo.INDEXLAST);

		String net = bundle.getString(IndexInfo.INDEXNET);
		String turnover = bundle.getString(IndexInfo.TURNOVER);
		String netPrecentage = bundle.getString(IndexInfo.INDEXNETPRECENTAGE);
		TDStockLog.d(TAG, "name=" + index_name + " , value=" + value
				+ " , net=" + net + " , turnover=" + turnover + " , "
				+ netPrecentage);
		if (value == null || net == null || turnover == null)
			return;
		if (index_name.equals(INDEX_NAME_HSCEI)) // 國企
		{
			boolean isNegative = net.indexOf("-") >= 0;
			try
			{
				_index_phsi.setText(StringUtils.formatScaleInteger(Double
						.parseDouble(value)));
			}
			catch (NumberFormatException e)
			{
				_index_phsi.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_phsi.postInvalidate();

			// DT, 2011/01/17, format to 0 d.p., need to be the same as iPhone
			// app
			// DT, 2011/02/01, follow 5 chars rule, not format to 0 d.p.
			// net = _formaterOnSacle1.format(Double.parseDouble(net));
			net = StringUtils.formatToFiveCharsRule(net);

			_index_phsi_net.setText(StringUtils.formatString(net,
					isNegative ? null : "+", null));
			_index_phsi_net.setTextColor(isNegative ? Color.RED
					: Color.GREEN);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_phsi_net.postInvalidate();
		}
		else if (index_name.equals(INDEX_NAME_HSI)) // 恆指
		{
			boolean isNegative = net.indexOf("-") >= 0;

			try
			{
				_index_hsi.setText(StringUtils.formatScaleInteger(Double
						.parseDouble(value)));

				/* Andy */
				// double netPercentage = Double.parseDouble(net) /
				// Double.parseDouble(value) * 100.00000d;

				// String netPercentageStr =
				// StringUtils.formatString(_formaterOnSacle2.format(netPercentage),
				// isNegative ? null : "+", null);
				// String netPercentageStr =
				// StringUtils.formatString(StringUtils.formatNumberByUsingTruncate(null,
				// netPercentage, 2), isNegative ? null : "+", null);

				// DT, 2011/02/01, do not round it to 1 d.p. at the beginning
				// net = _formaterOnSacle1.format(Double.parseDouble(net));

				String netStr = StringUtils.formatString(net,
						isNegative ? null : "+", null);

				// DT, 2011/01/17, format to 0 d.p., need to be the same as
				// iPhone app
				// DT, 2011/02/01, follow 5 chars rule, not format to 0 d.p.
				netStr = StringUtils.formatToFiveCharsRule(netStr);
				netPrecentage = StringUtils.formatNumberByNetPerectage(
						netPrecentage, 4);
				// DT, 2011/01/17, add 3 spaces between HSI net and net
				// percentage
				// _index_his_net.setText( netStr + "  (" + netPercentageStr +
				// "%)" );
				_index_his_net
						.setText(netStr + "  (" + netPrecentage + ")");

				_index_his_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e1)
			{
				_index_hsi.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
				_index_his_net.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
				e1.printStackTrace();
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_his_net.postInvalidate();
			// _index_his_turnover.setText(_formaterOnSacle2.format(Double.parseDouble(turnover)
			// / 100000.00d) +
			// getResources().getString(R.string.a_hundred_million));
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_his_turnover.postInvalidate();

			try
			{
				_index_his_turnover
						.setText(StringUtils.formatNumberByUsingTruncate(
								_formaterOnSacle2,
								Double.parseDouble(turnover) / 100000.00d,
								2)
								+ getResources().getString(
										R.string.a_hundred_million));
			}
			catch (Exception e)
			{
				_index_his_turnover
						.setText(CommonDefn.DEFAULT_FIELD_VALUE2);
			}

		}
	}

	public synchronized void updateIndex_Futures(String itemName,
			String value, String net)
	{
		if (itemName == null/* || value == null || net == null */)
			return;

		if (itemName.equals(INDEX_FUTURES_HSI_1))
		{
			try
			{
				_index_futures_hsi_1.setText(String.valueOf((int) Double
						.parseDouble(value)));
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_1.getText().toString().length() <= 0)
					_index_futures_hsi_1
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_futures_hsi_1.postInvalidate();
			// _index_futures_hsi_1_net.setText(net);

			// DT, 2011/01/17, format to 0 d.p., need to be the same as iPhone
			// app
			// DT, 2011/02/01, follow 5 chars rule, not format to 0 d.p.
			// net = _formaterOnSacle1.format(Double.parseDouble(net));
			try
			{
				boolean isNegative = net.indexOf("-") >= 0;
				net = StringUtils.formatToFiveCharsRule(net);
				_index_futures_hsi_1_net.setText(StringUtils.formatString(
						net, isNegative ? null : "+", null));
				_index_futures_hsi_1_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_1_net.getText().toString().length() <= 0)
					_index_futures_hsi_1_net
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_futures_hsi_1_net.postInvalidate();
		}
		else if (itemName.equals(INDEX_FUTURES_HSI_2))
		{
			try
			{
				_index_futures_hsi_2.setText(String.valueOf((int) Double
						.parseDouble(value)));
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_2.getText().toString().length() <= 0)
					_index_futures_hsi_2
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_futures_hsi_2.postInvalidate();
			// _index_futures_hsi_2_net.setText(net);

			// DT, 2011/01/17, format to 0 d.p., need to be the same as iPhone
			// app
			// DT, 2011/02/01, follow 5 chars rule, not format to 0 d.p.
			// net = _formaterOnSacle1.format(Double.parseDouble(net));
			try
			{
				boolean isNegative = net.indexOf("-") >= 0;
				net = StringUtils.formatToFiveCharsRule(net);
				_index_futures_hsi_2_net.setText(StringUtils.formatString(
						net, isNegative ? null : "+", null));
				_index_futures_hsi_2_net
						.setTextColor(net.indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
			}
			catch (Exception e)
			{
				if (_index_futures_hsi_2_net.getText().toString().length() <= 0)
					_index_futures_hsi_2_net
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			}
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _index_futures_hsi_2_net.postInvalidate();
		}
	}

	public synchronized void updateWorldIndex(String value, String net)
	{
		if (value == null || net == null)
			return;
		boolean isNegative = net.indexOf("-") >= 0;
		_worldindex_sse1.setText(StringUtils.formatScaleInteger(Double
				.parseDouble(value)));
		// modified by haibo, 2011-06-20, no need to do so and it cause the anr.
		// _worldindex_sse1.postInvalidate();
		// _worldindex_sse1_net.setText(net);

		// DT, 2011/02/01, follow 5 chars rule, not format to 0 d.p.
		// net = _formaterOnSacle1.format(Double.parseDouble(net));
		net = StringUtils.formatToFiveCharsRule(net);

		_worldindex_sse1_net.setText(StringUtils.formatString(net,
				isNegative ? null : "+", null));
		_worldindex_sse1_net.setTextColor(isNegative ? Color.RED
				: Color.GREEN);
		// modified by haibo, 2011-06-20, no need to do so and it cause the anr.
		// _worldindex_sse1_net.postInvalidate();
	}

	public synchronized void syncServerTimer(String time)
	{
		if (time == null)
		{
			_server_time.setText("");
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. //_server_time.postInvalidate();
		}
		else
		{
			_server_time.setText(time.length() >= 8 ? time.subSequence(0, 8)
					: time);
			// Log.d(TAG, "Time=" +_server_time.getText().toString() );
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. // _server_time.postInvalidate();
		}
	}

	public void updateCurrentStockInfo(final Bundle fromMsg)
	{
		try
		{
			if (fromMsg != null
					&& fromMsg.getString(StockInfo.ERRORMESSAGE) != null
					&& fromMsg.getString(StockInfo.ERRORMESSAGE).length() > 1)
			{
				TDStockLog.d(
						TAG,
						"ERRORMESSAGE>>> "
								+ fromMsg.getString(StockInfo.ERRORMESSAGE));
				try
				{
					String errMsg = fromMsg
							.getString(StockInfo.ERRORMESSAGE);
					if (errMsg.toLowerCase().indexOf(STOCK_NOT_FOUND_MSG) >= 0)
					{
						errMsg = "找不到此股號!";
					}

					if (_callbackErrMsgdialog == null)
					{
						_callbackErrMsgdialog = new CustomizeDialog(
								getMyOwnContext(), "", errMsg)
						{
							@Override
							public void onClick(View v)
							{
								// ** When OK Button is clicked, dismiss the
								// dialog *//*
								if (v == okButton)
								{
									dismiss();
									if (_lastStockCode != null
											&& _lastStockCode
													.length() >= 1)
									{
										_isNewStock = false;
										_current_stock_code
												.setText(_lastStockCode);
										// modified by haibo, 2011-06-20, no
										// need to do so and it cause the anr.
										// _current_stock_code.postInvalidate();
										_current_stock_code
												.clearFocus();
									}
									dealWithNewStockCodeComingFromEditor();
									Thread.yield();
									TDStockLog.d(TAG,
											" reset stock ocde here ?!");
								}

							}
						};
					}
					else
					{
						_callbackErrMsgdialog.setMsgContent(errMsg);
					}
					// if (_isNewStock)
					// {

					// }

					((Activity) CurrentStockInfoActivity.this.getParent())
							.runOnUiThread(new Runnable()
							{
								public void run()
								{
									_callbackErrMsgdialog.show();
								}
							});

				}
				catch (Exception e)
				{
					TDStockLog.d(
							TAG,
							e.getMessage() == null ? "unknow exception happened when stock code is empty!"
									: "exception: " + e.getMessage());
				}
				/*
				 * finally { stopSunFlowBuy(); }
				 */

				return; // there's a error (i.e. Stock Not Found)
			}

			if (fromMsg.getString(StockInfo.STOCKCHISHORTNAME) == null
					|| fromMsg.getString(StockInfo.NOMINAL) == null)
				return;
			// if (fromMsg.getString(StockInfo.NET) == null)
			// {
			// /*stopSunFlowBuy();*/
			// return;
			// }

			{
				String nature = (fromMsg.getString(StockInfo.NATURE) == null ? " nature= null"
						: fromMsg.getString(StockInfo.NATURE));
				// String warrantType =
				// (fromMsg.getString(StockInfo.WARRANTTYPE) == null ?
				// " warrant Type = null" :
				// fromMsg.getString(StockInfo.WARRANTTYPE));
				// Log.d(TAG, "nature>>> " + nature);
				// Log.d(TAG, "warrantType>>> " + warrantType);

				// -------------deal with nature & warrantType-------------

				resetLayoutByState("W".equalsIgnoreCase(nature));
				resetFieldValue("W".equalsIgnoreCase(nature), fromMsg);

				/*
				 * _field_value_4ReplaceMent[0] =
				 * (TextView)findViewById(R.id.current_stock_ex_ymd);
				 * _field_value_4ReplaceMent[1] =
				 * (TextView)findViewById(R.id.current_stock_div_ymd);
				 * _field_value_4ReplaceMent[2] =
				 * (TextView)findViewById(R.id.current_stock_div_value);
				 * _field_value_4ReplaceMent[3] =
				 * (TextView)findViewById(R.id.current_stock_rate_of_return);
				 * _field_value_4ReplaceMent[4] =
				 * (TextView)findViewById(R.id.current_stock_profitpershare);
				 * _field_value_4ReplaceMent[5] =
				 * (TextView)findViewById(R.id.current_stock_pe);
				 */

				// -------------deal with nature & warrantType-------------
			}

			try
			{
				if (_current_stock_nominal.getTag() == null
						|| !_current_stock_nominal
								.getTag()
								.toString()
								.equals(fromMsg
										.getString(StockInfo.NOMINAL)))
				{
					hightLightChangeItems(_current_stock_nominal.getTag(),
							fromMsg.getString(StockInfo.NOMINAL),
							fromMsg.getString(StockInfo.NET));
				}
				_current_stock_nominal.setTag(fromMsg
						.getString(StockInfo.NOMINAL));
			}
			catch (Exception e3)
			{
				e3.printStackTrace();
			}

			// if(!_current_stock_net.getText().toString().equals(fromMsg.getString(StockInfo.NET))){
			/*
			 * if(_current_stock_net.getTag() == null ||
			 * !_current_stock_net.getTag()
			 * .toString().equals(fromMsg.getString(StockInfo.NET))){
			 * if(_refreshNetBackground == null) { _refreshNetBackground = new
			 * ColorRefreshTask(CommonDefn.HIGHLIGHT_BACKGROUND_COLOR,
			 * MESSAGE_HANDLE_ID_UPDATE_BACKGROUND_NET); }
			 * _messageHandler.postDelayed(_refreshNetBackground, 50); }
			 */
			// _current_stock_net.setTag(fromMsg.getString(StockInfo.NET));

			// Ready for next Switching
			if (TradeAppInfo.TradeKeySwap_Ready)
			{
				String tmpStringValue, tmpStringValue2, tmpStringValue3;

				tmpStringValue = Trade_StockFunctionTools
						.FormatFullStockCode(String.valueOf(_stockCode));
				curViewStockInfo = new Trade_StockViewInfoItem(
						tmpStringValue,
						fromMsg.getString(StockInfo.STOCKCHISHORTNAME),
						null);

				tmpStringValue = fromMsg.getString(StockInfo.NOMINAL);
				tmpStringValue2 = fromMsg.getString(StockInfo.BIDPRICE);
				tmpStringValue3 = fromMsg.getString(StockInfo.ASKPRICE);
				curViewStockInfo.SetPriceInfo(tmpStringValue,
						tmpStringValue2, tmpStringValue3, false);
				tmpStringValue = fromMsg.getString(StockInfo.NET);
				tmpStringValue2 = fromMsg
						.getString(StockInfo.NETPERCENTAGE);
				curViewStockInfo.SetNetDiffPrice(tmpStringValue,
						tmpStringValue2);
				tmpStringValue = fromMsg.getString(StockInfo.LOTSIZE);
				curViewStockInfo.SetStepVolume(tmpStringValue);
				tmpStringValue = fromMsg.getString(StockInfo.CURRENCYCODE);
				curViewStockInfo.SetCurrencyCode(tmpStringValue);

				// Calculate the spread price
				tmpStringValue = Trade_StockFunctionTools
						.GetStockPriceSpread(curViewStockInfo
								.GetCurPriceText());
				curViewStockInfo.SetSpreadPrice(tmpStringValue);
			}

			String net = fromMsg.getString(StockInfo.NET);
			String netPercentage = fromMsg
					.getString(StockInfo.NETPERCENTAGE);
			String sharetraded = fromMsg.getString(StockInfo.SHARETRADED);
			String turnover = fromMsg.getString(StockInfo.TURNOVER);
			String prevcloseprice = fromMsg
					.getString(StockInfo.PREVCLOSEPRICE);
			String openprice = fromMsg.getString(StockInfo.OPENPRICE);
			String hightprice = fromMsg.getString(StockInfo.HIGHPRICE);
			TDStockLog.d(TAG, "NewStock=net>" + net + "," + netPercentage
					+ "," + sharetraded + "," + turnover + ","
					+ prevcloseprice + "," + openprice + "," + hightprice);
			TDStockLog.d(
					TAG,
					"NewStock="
							+ fromMsg.getString(StockInfo.STOCKCHISHORTNAME)
							+ " , nominal="
							+ fromMsg.getString(StockInfo.NOMINAL)
							+ " , net="
							+ fromMsg.getString(StockInfo.NET)
							+ " , netprecentage="
							+ fromMsg.getString(StockInfo.NETPERCENTAGE));
			TDStockLog.d(
					TAG,
					"NewStock="
							+ fromMsg.getString(StockInfo.SHARETRADED)
							+ " , "
							+ fromMsg.getString(StockInfo.TURNOVER)
							+ " , "
							+ fromMsg.getString(StockInfo.PREVCLOSEPRICE)
							+ " , "
							+ fromMsg.getString(StockInfo.OPENPRICE)
							+ " , "
							+ fromMsg.getString(StockInfo.BIDPRICE)
							+ " , "
							+ fromMsg.getString(StockInfo.ASKPRICE));

			_current_stock_chinese_short_name.setText(fromMsg
					.getString(StockInfo.STOCKCHISHORTNAME));
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _current_stock_chinese_short_name.postInvalidate();
			((ITDLApplication) CurrentStockInfoActivity.this
					.getApplicationContext()).setCurrentStockName(fromMsg
					.getString(StockInfo.STOCKCHISHORTNAME));
			_current_stock_nominal.setText(StringUtils.FormatNumber(
					StringUtils.ITDLNumber.STOCKPRICE,
					fromMsg.getString(StockInfo.NOMINAL)));
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _current_stock_nominal.postInvalidate();

			if (net == null || "".equals(net))
				net = "0.0";

			boolean isDown = net.indexOf("-") >= 0;
			_up_down.setImageResource(net == null ? null
					: isDown ? R.drawable.down_24_1 : R.drawable.up_24_1);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _up_down.postInvalidate();
			_current_stock_net
					.setText(net == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: StringUtils.FormatNumber(
									StringUtils.ITDLNumber.NET, net));
			int color = net == null ? Color.WHITE : isDown ? Color.RED
					: Color.GREEN;
			_current_stock_net.setTextColor(color);
			// _current_stock_net_percentage.setText("(" +
			// StringUtils.formatString(fromMsg.getString(StockInfo.NetPercentage),
			// isDown ? "-" : "+",null)+ "%)");
			// _current_stock_net_percentage.setText("(" +
			// StringUtils.formatString(fromMsg.getString(StockInfo.NetPercentage),
			// isDown ? "-" : "+",null)+ "%)");
			_current_stock_net_percentage
					.setText(netPercentage == null ? CommonDefn.DEFAULT_FIELD_VALUE
							: String.format(
									"(%s)",
									StringUtils
											.FormatNumber(
													StringUtils.ITDLNumber.NETPERCENTAGE,
													netPercentage)));
			_current_stock_net_percentage.setTextColor(color);

			try
			{
				// _current_stock_sharetraded.setText(_formaterOnSacle2.format(
				// Double.parseDouble(fromMsg.getString(StockInfo.ShareTraded))
				// / 1000.00d ) + "K" );
				// _current_stock_sharetraded.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.TURNOVER,
				// fromMsg.getString(StockInfo.SHARETRADED)));
				_current_stock_sharetraded
						.setText(sharetraded == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils.formatNumberByTurnove(
										sharetraded, 1));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_chinese_short_name.postInvalidate();
				// _current_stock_turnover.setText(_formaterOnSacle2.format(
				// Double.parseDouble(fromMsg.getString(StockInfo.Turnover)) /
				// 1000.00d ) + "K" );
				// modify by ouyangzhihui 20110801 format number round down
				_current_stock_turnover
						.setText(turnover == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: String.format("$%s", StringUtils
										.formatNumberByTurnove(
												turnover, 1)));
				// _current_stock_turnover.setText(String.format("$%s",
				// StringUtils.FormatNumber(StringUtils.ITDLNumber.TURNOVER,
				// fromMsg.getString(StockInfo.TURNOVER))));

				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_turnover.postInvalidate();

				_current_stock_prevcloseprice
						.setText(prevcloseprice == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.FormatNumber(
												StringUtils.ITDLNumber.STOCKPRICE,
												prevcloseprice));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_prevcloseprice.postInvalidate();
				_current_stock_openprice
						.setText(openprice == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.FormatNumber(
												StringUtils.ITDLNumber.STOCKPRICE,
												openprice));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_openprice.postInvalidate();
				_current_stock_highprice
						.setText(hightprice == null ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.FormatNumber(
												StringUtils.ITDLNumber.STOCKPRICE,
												hightprice));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_highprice.postInvalidate();
				_current_stock_lowprice.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.STOCKPRICE,
						fromMsg.getString(StockInfo.LOWPRICE)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_lowprice.postInvalidate();
				_current_stock_bidprice.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.STOCKPRICE,
						fromMsg.getString(StockInfo.BIDPRICE)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_bidprice.postInvalidate();
				_current_stock_askprice.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.STOCKPRICE,
						fromMsg.getString(StockInfo.ASKPRICE)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_askprice.postInvalidate();
			}
			catch (NumberFormatException e2)
			{
				TDStockLog.d(TAG, "NewStock=" + e2.toString());
				e2.printStackTrace();
			}

			if (((ITDLApplication) getApplicationContext()).getDataMode() != CommonDefn.DataMode.Delay)
			{
				try
				{
					// _current_stock_bid_share_1.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.BID_SHARE_1))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_share_1.postInvalidate();
					handleBidAndAsk(_current_stock_bid_share_1,
							fromMsg.getString(StockInfo.BID_SHARE_1));

					// _current_stock_bid_queue_1.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.BID_QUEUE_1)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_queue_1.postInvalidate();
					handleTranCNT(_current_stock_bid_queue_1,
							fromMsg.getString(StockInfo.BID_QUEUE_1), ""); // modify
					// by
					// zor(ouyangzhihui)

					// _current_stock_bid_share_2.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.BID_SHARE_2))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_share_2.postInvalidate();
					handleBidAndAsk(_current_stock_bid_share_2,
							fromMsg.getString(StockInfo.BID_SHARE_2));
					// _current_stock_bid_queue_2.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.BID_QUEUE_2)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_queue_2.postInvalidate();
					handleTranCNT(_current_stock_bid_queue_2,
							fromMsg.getString(StockInfo.BID_QUEUE_2), "");

					// _current_stock_bid_share_3.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.BID_SHARE_3))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_share_3.postInvalidate();
					handleBidAndAsk(_current_stock_bid_share_3,
							fromMsg.getString(StockInfo.BID_SHARE_3));
					// _current_stock_bid_queue_3.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.BID_QUEUE_3)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_queue_3.postInvalidate();
					handleTranCNT(_current_stock_bid_queue_3,
							fromMsg.getString(StockInfo.BID_QUEUE_3), "");

					// _current_stock_bid_share_4.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.BID_SHARE_4))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_share_4.postInvalidate();
					handleBidAndAsk(_current_stock_bid_share_4,
							fromMsg.getString(StockInfo.BID_SHARE_4));
					// _current_stock_bid_queue_4.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.BID_QUEUE_4)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_queue_4.postInvalidate();
					handleTranCNT(_current_stock_bid_queue_4,
							fromMsg.getString(StockInfo.BID_QUEUE_4), "");

					// _current_stock_bid_share_5.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.BID_SHARE_5))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_share_5.postInvalidate();
					handleBidAndAsk(_current_stock_bid_share_5,
							fromMsg.getString(StockInfo.BID_SHARE_5));
					// _current_stock_bid_queue_5.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.BID_QUEUE_5)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_bid_queue_5.postInvalidate();
					handleTranCNT(_current_stock_bid_queue_5,
							fromMsg.getString(StockInfo.BID_QUEUE_5), "");

					// _current_stock_ask_share_1.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.ASK_SHARE_1))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_share_1.postInvalidate();
					handleBidAndAsk(_current_stock_ask_share_1,
							fromMsg.getString(StockInfo.ASK_SHARE_1));
					// _current_stock_ask_queue_1.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.ASK_QUEUE_1)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_queue_1.postInvalidate();
					handleTranCNT(_current_stock_ask_queue_1,
							fromMsg.getString(StockInfo.ASK_QUEUE_1),
							"( )");

					// _current_stock_ask_share_2.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.ASK_SHARE_2))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_share_2.postInvalidate();
					handleBidAndAsk(_current_stock_ask_share_2,
							fromMsg.getString(StockInfo.ASK_SHARE_2));
					// _current_stock_ask_queue_2.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.ASK_QUEUE_2)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_queue_2.postInvalidate();
					handleTranCNT(_current_stock_ask_queue_2,
							fromMsg.getString(StockInfo.ASK_QUEUE_2),
							"( )");

					// _current_stock_ask_share_3.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.ASK_SHARE_3))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_share_3.postInvalidate();
					handleBidAndAsk(_current_stock_ask_share_3,
							fromMsg.getString(StockInfo.ASK_SHARE_3));
					// _current_stock_ask_queue_3.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.ASK_QUEUE_3)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_queue_3.postInvalidate();
					handleTranCNT(_current_stock_ask_queue_3,
							fromMsg.getString(StockInfo.ASK_QUEUE_3),
							"( )");

					// _current_stock_ask_share_4.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.ASK_SHARE_4))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_share_4.postInvalidate();
					handleBidAndAsk(_current_stock_ask_share_4,
							fromMsg.getString(StockInfo.ASK_SHARE_4));
					// _current_stock_ask_queue_4.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.ASK_QUEUE_4)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_queue_4.postInvalidate();
					handleTranCNT(_current_stock_ask_queue_4,
							fromMsg.getString(StockInfo.ASK_QUEUE_4),
							"( )");

					// _current_stock_ask_share_5.setText(
					// Integer.parseInt(fromMsg.getString(StockInfo.ASK_SHARE_5))
					// / 1000 + "K" );
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_share_5.postInvalidate();
					handleBidAndAsk(_current_stock_ask_share_5,
							fromMsg.getString(StockInfo.ASK_SHARE_5));
					// _current_stock_ask_queue_5.setText(String.format("(%s)",
					// fromMsg.getString(StockInfo.ASK_QUEUE_5)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. //
					// _current_stock_ask_queue_5.postInvalidate();
					handleTranCNT(_current_stock_ask_queue_5,
							fromMsg.getString(StockInfo.ASK_QUEUE_5),
							"( )");

					// stop stock info.
					String shareTraded = _current_stock_sharetraded
							.getText().toString().trim();
					/*
					 * String bidPrice =
					 * _current_stock_bidprice.getText().toString().trim();
					 * String askPrice =
					 * _current_stock_askprice.getText().toString().trim();
					 */
					shareTraded = shareTraded.length() > 0 ? shareTraded
							.substring(0, shareTraded.length() - 1)
							: shareTraded; // modify
					// by
					// ouyangzhihui
					// 2011-06-09
					// _current_stock_bid_queue_1.
					if ("Y".equalsIgnoreCase(fromMsg
							.getString(StockInfo.SUSPSTOCK)))
					{ // modified by
						// haibo,
						// 2011-06-30
						/*
						 * if("0.0".equals(shareTraded) &&
						 * "0.000".equals(bidPrice) &&
						 * "0.000".equals(askPrice)){
						 */
						_current_stock_bid_share_1.setText(getResources()
								.getString(R.string.stock_stop));
						_current_stock_bid_queue_1.setText(getResources()
								.getString(R.string.stock_bidask));
						_current_stock_bid_share_1
								.setGravity(Gravity.RIGHT);
						_current_stock_bid_queue_1
								.setGravity(Gravity.LEFT);
						_current_stock_bid_share_1
								.setBackgroundColor(Color.RED);
						_current_stock_bid_queue_1
								.setBackgroundColor(Color.RED);
					}
					else
					{
						int bgcolor = _current_stock_bid
								.getDrawingCacheBackgroundColor();
						_current_stock_bid_share_1
								.setGravity(Gravity.LEFT);
						_current_stock_bid_queue_1
								.setGravity(Gravity.RIGHT);
						_current_stock_bid_share_1
								.setBackgroundColor(bgcolor);
						_current_stock_bid_queue_1
								.setBackgroundColor(bgcolor);
					}
				}
				catch (NumberFormatException e1)
				{
					e1.printStackTrace();

				}
				/*
				 * finally { stopSunFlowBuy(); }
				 */

				String tradeticker_1 = fromMsg
						.getString(StockInfo.TRADETICKER1) == null ? ""
						: fromMsg.getString(StockInfo.TRADETICKER1)
								.replace('^', '#');
				String[] tradeticker_1_elements = tradeticker_1
						.split("[#]");
				/*
				 * if(tradeticker_1_elements.length >= 4) { if(
				 * tradeticker_1_elements[0].length() >=4) { String time =
				 * tradeticker_1_elements[0].substring(0, 2) + ":" +
				 * tradeticker_1_elements[0].substring(2, 4) ; String trade =
				 * (int)Double.parseDouble( tradeticker_1_elements[2]) / 1000 +
				 * "K" ; String price = tradeticker_1_elements[3]; String
				 * htmlContent =String.format(
				 * "<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font> </span>"
				 * , time, trade,
				 * StringUtils.FormatNumber(StringUtils.ITDLNumber
				 * .STOCKPRICE,price));
				 * _current_stock_tradeticker_1.setText(Html
				 * .fromHtml(htmlContent)); // modified by haibo, 2011-06-20, no
				 * need to do so and it cause the anr.
				 * _current_stock_tradeticker_1.postInvalidate(); } }
				 */
				handleTradeticker(_tradeticker_textviews[0],
						tradeticker_1_elements);

				String tradeticker_2 = fromMsg
						.getString(StockInfo.TRADETICKER2) == null ? ""
						: fromMsg.getString(StockInfo.TRADETICKER2)
								.replace('^', '#');
				String[] tradeticker_2_elements = tradeticker_2
						.split("[#]");
				/*
				 * if(tradeticker_2_elements.length >= 4) {
				 * if(tradeticker_2_elements[0].length() >=4) { String time =
				 * tradeticker_2_elements[0].substring(0, 2) + ":" +
				 * tradeticker_2_elements[0].substring(2, 4) ; String trade =
				 * (int)Double.parseDouble( tradeticker_2_elements[2]) / 1000 +
				 * "K" ; String price = tradeticker_2_elements[3]; String
				 * htmlContent =String.format(
				 * "<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font> </span>"
				 * , time, trade,
				 * StringUtils.FormatNumber(StringUtils.ITDLNumber
				 * .STOCKPRICE,price));
				 * _current_stock_tradeticker_2.setText(Html
				 * .fromHtml(htmlContent)); // modified by haibo, 2011-06-20, no
				 * need to do so and it cause the anr.
				 * _current_stock_tradeticker_2.postInvalidate(); } }
				 */
				handleTradeticker(_tradeticker_textviews[1],
						tradeticker_2_elements);

				String tradeticker_3 = fromMsg
						.getString(StockInfo.TRADETICKER3) == null ? ""
						: fromMsg.getString(StockInfo.TRADETICKER3)
								.replace('^', '#');
				String[] tradeticker_3_elements = tradeticker_3
						.split("[#]");
				/*
				 * if(tradeticker_3_elements.length >= 4) { if(
				 * tradeticker_3_elements[0].length()>=4){ String time =
				 * tradeticker_3_elements[0].substring(0, 2) + ":" +
				 * tradeticker_3_elements[0].substring(2, 4) ; String trade =
				 * (int)Double.parseDouble( tradeticker_3_elements[2]) / 1000 +
				 * "K" ; String price = tradeticker_3_elements[3]; String
				 * htmlContent =String.format(
				 * "<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font> </span>"
				 * , time, trade,
				 * StringUtils.FormatNumber(StringUtils.ITDLNumber
				 * .STOCKPRICE,price));
				 * _current_stock_tradeticker_3.setText(Html
				 * .fromHtml(htmlContent)); // modified by haibo, 2011-06-20, no
				 * need to do so and it cause the anr.
				 * _current_stock_tradeticker_3.postInvalidate(); } }
				 */

				handleTradeticker(_tradeticker_textviews[2],
						tradeticker_3_elements);

				String tradeticker_4 = fromMsg
						.getString(StockInfo.TRADETICKER4) == null ? ""
						: fromMsg.getString(StockInfo.TRADETICKER4)
								.replace('^', '#');
				String[] tradeticker_4_elements = tradeticker_4
						.split("[#]");
				/*
				 * if(tradeticker_4_elements.length >= 4) {
				 * if(tradeticker_4_elements[0].length() >=4) { String time =
				 * tradeticker_4_elements[0].substring(0, 2) + ":" +
				 * tradeticker_4_elements[0].substring(2, 4) ; String trade =
				 * (int)Double.parseDouble( tradeticker_4_elements[2]) / 1000 +
				 * "K" ; String price = tradeticker_4_elements[3]; String
				 * htmlContent =String.format(
				 * "<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font> </span>"
				 * , time, trade,
				 * StringUtils.FormatNumber(StringUtils.ITDLNumber
				 * .STOCKPRICE,price));
				 * _current_stock_tradeticker_4.setText(Html
				 * .fromHtml(htmlContent)); // modified by haibo, 2011-06-20, no
				 * need to do so and it cause the anr.
				 * _current_stock_tradeticker_4.postInvalidate(); } }
				 */
				handleTradeticker(_tradeticker_textviews[3],
						tradeticker_4_elements);

				String tradeticker_5 = fromMsg
						.getString(StockInfo.TRADETICKER5) == null ? ""
						: fromMsg.getString(StockInfo.TRADETICKER5)
								.replace('^', '#');
				String[] tradeticker_5_elements = tradeticker_5
						.split("[#]");
				/*
				 * if(tradeticker_5_elements.length >= 4) { if(
				 * tradeticker_5_elements[0].length() >=4) { String time =
				 * tradeticker_5_elements[0].substring(0, 2) + ":" +
				 * tradeticker_5_elements[0].substring(2, 4) ; String trade =
				 * (int)Double.parseDouble( tradeticker_5_elements[2]) / 1000 +
				 * "K" ; String price = tradeticker_5_elements[3]; String
				 * htmlContent =String.format(
				 * "<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font> </span>"
				 * , time, trade,
				 * StringUtils.FormatNumber(StringUtils.ITDLNumber
				 * .STOCKPRICE,price));
				 * _current_stock_tradeticker_5.setText(Html
				 * .fromHtml(htmlContent)); // modified by haibo, 2011-06-20, no
				 * need to do so and it cause the anr.
				 * _current_stock_tradeticker_5.postInvalidate(); } }
				 */

				handleTradeticker(_tradeticker_textviews[4],
						tradeticker_5_elements);
			}
			_current_stock_lotsize.setText(fromMsg
					.getString(StockInfo.LOTSIZE));
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _current_stock_lotsize.postInvalidate();
			/*
			 * _current_stock_ex_ymd.setText(resetDateFormat(fromMsg.getString(
			 * StockInfo .EXYMD))); _current_stock_ex_ymd.postInvalidate();
			 */// --01
			try
			{
				/*
				 * double yearHigh =
				 * Double.parseDouble(fromMsg.getString(StockInfo.YearHigh));
				 * _current_stock_year_high
				 * .setText(_formaterOnSacle2.format(yearHigh));
				 */

				_current_stock_year_high.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.HIGHTLOW,
						fromMsg.getString(StockInfo.YEARHIGH)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_year_high.postInvalidate();
			}
			catch (NumberFormatException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			/*
			 * _current_stock_div_ymd.setText(resetDateFormat(fromMsg.getString(
			 * StockInfo .DIVYMD))); _current_stock_div_ymd.postInvalidate();
			 */// --02

			try
			{
				/*
				 * double yearLow =
				 * Double.parseDouble(fromMsg.getString(StockInfo.YearLow));
				 * _current_stock_year_low
				 * .setText(_formaterOnSacle2.format(yearLow));
				 */
				_current_stock_year_low.setText(StringUtils.FormatNumber(
						StringUtils.ITDLNumber.HIGHTLOW,
						fromMsg.getString(StockInfo.YEARLOW)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_year_low.postInvalidate();
			}
			catch (NumberFormatException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			/*
			 * double nominal = 0.00d; try { nominal =
			 * Double.parseDouble(fromMsg.getString(StockInfo.NOMINAL)); }
			 * catch(Exception e) { } double divValue = 0.00d; try { divValue =
			 * Double.parseDouble(fromMsg.getString(StockInfo.DIVVALUE)); }
			 * catch(Exception e) { }
			 */

			// DT, 2011/01/14, format to 0 d.p., need to be the same as iPhone
			// app
			// _current_stock_div_value.setText(Math.abs(divValue) <= 0.000001d
			// ? CommonDefn.DEFAULT_FIELD_VALUE : String.valueOf(divValue) +
			// getResources().getString(R.string.cent) );
			/*
			 * _current_stock_div_value.setText(Math.abs(divValue) <= 0.000001d
			 * ? CommonDefn.DEFAULT_FIELD_VALUE :
			 * StringUtils.formatToDp(String.valueOf(divValue), 0) +
			 * getResources().getString(R.string.cent) );
			 * _current_stock_div_value.postInvalidate();
			 */// --03

			// DT, 2011/01/14, shows "---" if not available, need to be the same
			// as iPhone app
			// TODO: _current_stock_rate_of_return is too different from web
			// site www.aastocks.com, if the formular correct?
			// _current_stock_rate_of_return.setText( (Math.abs(divValue) <=
			// 0.000001d || Math.abs(nominal) <= 0.000001d ) ?
			// CommonDefn.DEFAULT_FIELD_VALUE : _formaterOnSacle2.format(
			// divValue/ nominal * 100) + "%");
			/*
			 * _current_stock_rate_of_return.setText( (Math.abs(divValue) <=
			 * 0.000001d || Math.abs(nominal) <= 0.000001d ) ?
			 * CommonDefn.DEFAULT_FIELD_VALUE2 : _formaterOnSacle2.format(
			 * divValue/ nominal * 100) + "%");
			 * _current_stock_rate_of_return.postInvalidate();
			 */// --04
				// double profitpershare = 0.00d;
			try
			{
				// profitpershare =
				// Double.parseDouble(fromMsg.getString(StockInfo.PROFITPERSHARE));

				/*
				 * String profitPershareStr = Math.abs(profitpershare) <=
				 * 0.000001d ? CommonDefn.DEFAULT_FIELD_VALUE :
				 * String.valueOf(profitpershare);
				 */

				// DT, 2011/01/14, format to 4 d.p., need to be the same as
				// iPhone app
				// _current_stock_profitpershare.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,
				// profitPershareStr));
				/*
				 * _current_stock_profitpershare.setText(StringUtils.formatToDp(
				 * profitPershareStr , 4));
				 * _current_stock_profitpershare.postInvalidate();
				 */// --05

				/*
				 * String peStr = (Math.abs(profitpershare) <= 0.000001d ||
				 * Math.abs(nominal) <= 0.000001d ) ?
				 * CommonDefn.DEFAULT_FIELD_VALUE : String.valueOf((nominal/
				 * profitpershare)) ;
				 * _current_stock_pe.setText(StringUtils.FormatNumber
				 * (StringUtils.ITDLNumber.STOCKPRICE, peStr) );
				 * _current_stock_pe.postInvalidate();
				 */// --06

				try
				{
					_current_stock_rsi9.setText(StringUtils.FormatNumber(
							StringUtils.ITDLNumber.STOCKPRICE,
							fromMsg.getString(StockInfo.RSI9)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. _current_stock_rsi9.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try
				{
					_current_stock_rsi14.setText(StringUtils.FormatNumber(
							StringUtils.ITDLNumber.STOCKPRICE,
							fromMsg.getString(StockInfo.RSI14)));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. _current_stock_rsi14.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// by ouyangzhihui 2011-8-01
				try
				{
					_current_stock_currency
							.setText(fromMsg
									.getString(StockInfo.CURRENCYCODE) == null ? CommonDefn.DEFAULT_FIELD_VALUE
									: fromMsg.getString(StockInfo.CURRENCYCODE));
				}
				catch (Exception e)
				{
					_current_stock_currency
							.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				}

				// DT, 2011/01/14, show 3 d.p., need to be the same as iPhone
				// app
				// _current_stock_day_10_avg.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,fromMsg.getString(StockInfo.DAY10AVG)));
				// _current_stock_day_20_avg.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,fromMsg.getString(StockInfo.DAY20AVG)));
				// _current_stock_day_50_avg.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,fromMsg.getString(StockInfo.DAY50AVG)));

				try
				{
					_current_stock_day_10_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY10AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_10_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_20_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY20AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_20_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_50_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY50AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_50_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_100_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY100AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_100_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_200_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY200AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_200_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try
				{
					_current_stock_day_250_avg
							.setText(StringUtils.formatToDp(fromMsg
									.getString(StockInfo.DAY250AVG), 3));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_day_250_avg.postInvalidate();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				if (sunFlowerView1 != null && sunFlowerView1.isRunning())
				{
					stopSunflower();
				}

			}
			catch (Exception e)
			{
				TDStockLog.d(TAG, "NewStock=" + e.toString());
				e.printStackTrace();
			}

		}
		catch (Exception e)
		{
			TDStockLog.d(TAG, "NewStock=" + e.toString());
			e.printStackTrace();
		}
	}

	public synchronized void update_BID_QUEUE(final String value,
			final TextView[] left, final TextView[] right)
	{

		class BIDThread extends Thread
		{
			String		value;
			TextView[]	left;
			TextView[]	right;
			final int		COUNTER	= SPREAD_COUNTER;

			public BIDThread(final String value, final TextView[] left,
					final TextView[] right)
			{
				super();
				this.value = value;
				this.left = left;
				this.right = right;
			}

			@Override
			public void run()
			{
				int seq_number = 0;
				int identity = 0;
				int seq = 0;
				int childCount = 0;
				for (int index = 0; index < SPREAD_COUNTER; index++)
				{
					TextView tv = left[index];
					tv.setText("");
					tv.setBackgroundDrawable(null);
					// tv.postInvalidate(); //modified by haibo, 2011-06-14, no
					// need to do so to avoid anr
				}

				for (int index = 0; index < SPREAD_COUNTER; index++)
				{
					TextView tv = right[index];
					tv.setText("");

					tv.setBackgroundDrawable(null);
					// tv.postInvalidate(); //modified by haibo, 2011-06-14, no
					// need to do so to avoid anr
				}

				if (value == null || value.length() < 1)
				{
					return;
				}
				String[] broker_bid_queue_spread_elements = value.replace(
						'^', '#').split("[#]");

				boolean isTopOne = true;

				String charArr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
				String numArr = "1234567890";

				for (int index = 0, len = broker_bid_queue_spread_elements.length; index < len
						&& childCount < 2 * SPREAD_COUNTER; index++)
				{
					boolean isMinus = broker_bid_queue_spread_elements[index]
							.indexOf('-') >= 0 ? true : false;
					boolean isCompanyStock = false;
					for (String code : _securities_company_code)
					{
						if (code.equals(broker_bid_queue_spread_elements[index]))
						{
							isCompanyStock = true;
							break;
						}
					}

					if (!isCompanyStock)
					{
						isCompanyStock = _securities_company_name
								.equals(broker_bid_queue_spread_elements[index]);
					}

					int currBackGroundColor = isMinus ? 0xff999999
							: 0xff4b89d0;
					currBackGroundColor = isCompanyStock ? 0xffB2F6FE
							: currBackGroundColor;
					if (isTopOne && isMinus)
					{
						isTopOne = false;
					}

					seq_number = isMinus ? Integer.parseInt(
							broker_bid_queue_spread_elements[index], 10)
							: seq_number;

					// currentContainer = seq_number < SEQ_FOURTEENTH ?
					// _broker_bid_queue_spread_right :
					// _broker_bid_queue_spread_left ;

					// identity= (childCount < COUNTER) ?
					// VIEW_BID_SPREAD_ID_START_LEFT + index : (
					// VIEW_BID_SPREAD_ID_START_RIGHT + (seq++)) ;
					if (childCount < COUNTER)
					{
						identity = VIEW_BID_SPREAD_ID_START_LEFT + index;
					}
					else
					{
						seq++;
						identity = VIEW_BID_SPREAD_ID_START_RIGHT
								+ (seq - 1);
					}

					// TextView currTextView = (TextView)findViewById(identity)
					// ;
					TextView currTextView = (childCount < COUNTER) ? left[index]
							: right[seq - 1];

					currTextView.setBackgroundColor(currBackGroundColor);

					String tmpCode = broker_bid_queue_spread_elements[index];
					if (tmpCode != null && !"".equals(tmpCode))
					{
						if (charArr.contains(tmpCode.substring(0, 1))) // char
						{
							if (tmpCode.length() > 9)
								tmpCode = tmpCode.substring(0, 9);
						}
						else if (!numArr
								.contains(tmpCode.substring(0, 1))) // num
						{
							if (tmpCode.length() > 4)
								tmpCode = tmpCode.substring(0, 4);
						}
					}
					currTextView.setText(tmpCode);
					if (isCompanyStock)
					{
						currTextView.setTextColor(Color.BLACK);
					}
					else
					{
						currTextView.setTextColor(Color.WHITE);
					}
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. currTextView.postInvalidate();
					childCount++;
				}

				while (-1 * seq_number < SPREAD_COUNTER
						&& childCount < 2 * SPREAD_COUNTER)
				{
					seq_number--;
					identity = (childCount < COUNTER) ? (identity + 1)
							: (VIEW_BID_SPREAD_ID_START_RIGHT + (seq++));
					int currBackGroundColor = 0xff999999;
					// TextView currTextView = (TextView)findViewById(identity)
					// ;
					TextView currTextView = (childCount < COUNTER) ? left[identity
							- VIEW_BID_SPREAD_ID_START_LEFT]
							: right[seq - 1];
					currTextView.setBackgroundColor(currBackGroundColor);
					currTextView.setText(String.format("%d", seq_number));
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. currTextView.postInvalidate();
					childCount++;
				}

				super.run();
			}

		}

		new Thread()
		{
			public void run()
			{
				_messageHandler.post(new BIDThread(value, left, right));
			}
		}.start();

	}

	public synchronized void update_ASK_QUEUE(final String value,
			final TextView[] left, final TextView[] right)
	{
		class ASKThread extends Thread
		{
			String		value;
			TextView[]	left;
			TextView[]	right;
			final int		COUNTER	= SPREAD_COUNTER;

			public ASKThread(final String value, final TextView[] left,
					final TextView[] right)
			{
				super();
				this.value = value;
				this.left = left;
				this.right = right;
			}

			@Override
			public void run()
			{
				int seq_number = 0;
				int identity = 0;
				int seq = 0;
				int childCount = 0;
				for (int index = 0; index < SPREAD_COUNTER; index++)
				{
					TextView tv = left[index];
					tv.setText("");
					tv.setBackgroundDrawable(null);
					// tv.postInvalidate(); //modified by haibo, 2011-06-14, no
					// need to do so to avoid anr
				}

				for (int index = 0; index < SPREAD_COUNTER; index++)
				{
					TextView tv = right[index];
					tv.setText("");

					tv.setBackgroundDrawable(null);
					// tv.postInvalidate(); //modified by haibo, 2011-06-14, no
					// need to do so to avoid anr
				}
				if (value == null || value.length() < 1)
				{
					return;
				}
				String[] broker_ask_queue_spread_elements = value.replace(
						'^', '#').split("[#]");

				String charArr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
				String numArr = "1234567890";
				for (int index = 0, len = broker_ask_queue_spread_elements.length; index < len
						&& childCount < 2 * SPREAD_COUNTER; index++)
				{
					boolean isPostiveNumber = broker_ask_queue_spread_elements[index]
							.indexOf('+') >= 0 ? true : false;
					boolean isCompanyStock = false;
					for (String code : _securities_company_code)
					{
						if (code.equals(broker_ask_queue_spread_elements[index]))
						{
							isCompanyStock = true;
							break;
						}
					}

					if (!isCompanyStock)
					{
						isCompanyStock = _securities_company_name
								.equals(broker_ask_queue_spread_elements[index]);
					}

					int currBackGroundColor = isPostiveNumber ? 0xff999999
							: 0xFFFFB075;// 0xffffb554;
					currBackGroundColor = isCompanyStock ? 0xffB2F6FE
							: currBackGroundColor;
					seq_number = isPostiveNumber ? Integer.parseInt(
							broker_ask_queue_spread_elements[index]
									.substring(1), 10) : seq_number;

					// identity =(childCount < COUNTER) ?
					// VIEW_ASK_SPREAD_ID_START_LEFT + index :
					// VIEW_ASK_SPREAD_ID_START_RIGHT + (seq++) ;
					if (childCount < COUNTER)
					{
						identity = VIEW_ASK_SPREAD_ID_START_LEFT + index;
					}
					else
					{
						seq++;
						identity = VIEW_ASK_SPREAD_ID_START_RIGHT
								+ (seq - 1);
					}

					// TextView currTextView = (TextView)findViewById(identity)
					// ;
					TextView currTextView = (childCount < COUNTER) ? left[index]
							: right[seq - 1];
					currTextView.setBackgroundColor(currBackGroundColor);

					String tmpCode = broker_ask_queue_spread_elements[index];
					if (tmpCode != null && !"".equals(tmpCode))
					{
						if (charArr.contains(tmpCode.substring(0, 1))) // char
						{
							if (tmpCode.length() > 9)
								tmpCode = tmpCode.substring(0, 9);
						}
						else if (!numArr
								.contains(tmpCode.substring(0, 1))) // num
						{
							if (tmpCode.length() > 4)
								tmpCode = tmpCode.substring(0, 4);
						}
					}
					currTextView.setText(tmpCode);
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. currTextView.postInvalidate();

					childCount++;
				}
				while (seq_number < SPREAD_COUNTER
						&& childCount < 2 * SPREAD_COUNTER)
				{
					seq_number++;

					identity = (childCount < COUNTER) ? identity + 1
							: VIEW_ASK_SPREAD_ID_START_RIGHT + (seq++);
					int currBackGroundColor = 0xff999999;
					// TextView currTextView = (TextView)findViewById(identity)
					// ;
					TextView currTextView = (childCount < COUNTER) ? left[identity
							- VIEW_ASK_SPREAD_ID_START_LEFT]
							: right[seq - 1];

					currTextView.setBackgroundColor(currBackGroundColor);
					currTextView.setText(String.format("+%d", seq_number));

					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. currTextView.postInvalidate();
					childCount++;
				}

			}
		}

		new Thread()
		{
			public void run()
			{
				_messageHandler.post(new ASKThread(value, left, right));
			}
		}.start();
	}

	public synchronized void init_broker_view()
	{
		// initialize the first half of the queue
		LinearLayout[] containers = { _broker_bid_queue_spread_left,
				_broker_bid_queue_spread_right,
				_broker_ask_queue_spread_left,
				_broker_ask_queue_spread_right };
		int[] ids_start = { VIEW_BID_SPREAD_ID_START_LEFT,
				VIEW_BID_SPREAD_ID_START_RIGHT,
				VIEW_ASK_SPREAD_ID_START_LEFT,
				VIEW_ASK_SPREAD_ID_START_RIGHT };
		int[] colors = { Color.WHITE, Color.WHITE, Color.BLACK, Color.BLACK };
		TextView[][] tvs = { _BID_LEFT_TEXTVIEWS, _BID_RIGHT_TEXTVIEWS,
				_ASK_LEFT_TEXTVIEWS, _ASK_RIGHT_TEXTVIEWS };
		for (int item = 0, itemLength = containers.length; item < itemLength; item++)
		{
			LinearLayout currentContainer = containers[item];
			int id_start = ids_start[item];
			int text_color = colors[item];
			TextView[] curr_tvs = tvs[item];
			for (int index = 0; index < SPREAD_COUNTER; index++)
			{
				TextView currTextView = new TextView(this);
				currTextView.setId(id_start + index);
				currTextView.setTextColor(text_color);
				currTextView.setTextSize(16);
				currTextView.setGravity(Gravity.LEFT);
				currTextView.setPadding(20, 0, 0, 0);
				// currTextView.setWidth(75);
				currTextView.setWidth(79);
				// currTextView.setWidth((_display.getWidth() -2 /4));
				currTextView.setHeight(36);
				currentContainer.addView(currTextView);
				curr_tvs[index] = currTextView;
			}
		}

		// initialize chinese name
		LinearLayout[] containers_ch = { _broker_bid_queue_spread_left_ch,
				_broker_bid_queue_spread_right_ch,
				_broker_ask_queue_spread_left_ch,
				_broker_ask_queue_spread_right_ch };
		int[] ids_start_ch = { VIEW_BID_SPREAD_ID_START_LEFT_CH,
				VIEW_BID_SPREAD_ID_START_RIGHT_CH,
				VIEW_ASK_SPREAD_ID_START_LEFT_CH,
				VIEW_ASK_SPREAD_ID_START_RIGHT_CH };
		TextView[][] tvs_ch = { _BID_LEFT_TEXTVIEWS_CH,
				_BID_RIGHT_TEXTVIEWS_CH, _ASK_LEFT_TEXTVIEWS_CH,
				_ASK_RIGHT_TEXTVIEWS_CH };
		for (int item = 0, itemLength = containers.length; item < itemLength; item++)
		{
			LinearLayout currentContainer = containers_ch[item];
			int id_start = ids_start_ch[item];
			int text_color = colors[item];
			TextView[] curr_tvs = tvs_ch[item];
			for (int index = 0; index < SPREAD_COUNTER; index++)
			{
				TextView currTextView = new TextView(this);
				currTextView.setId(id_start + index);
				currTextView.setTextColor(text_color);
				currTextView.setTextSize(16);
				currTextView.setGravity(Gravity.CENTER);
				currTextView.setSingleLine(true);
				// currTextView.setWidth(75);
				// currTextView.setWidth((_display.getWidth() -2 /4));
				currTextView.setWidth(79);
				currTextView.setHeight(36);
				currentContainer.addView(currTextView);
				curr_tvs[index] = currTextView;
			}
		}

	}

	public synchronized void updateBackground(int handlerId, int color)
	{
		switch (handlerId)
		{
			case MESSAGE_HANDLE_ID_UPDATE_BACKGROUND_NET:
				if (color <= 0)
				{
					_current_stock_net.setBackgroundDrawable(null);
					_current_stock_net_percentage
							.setBackgroundDrawable(null);
					int txtColor = _current_stock_net.getText().toString()
							.indexOf("-") >= 0 ? Color.RED : Color.GREEN;
					_current_stock_net.setTextColor(txtColor);
					_current_stock_net_percentage.setTextColor(txtColor);
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. _current_stock_net.postInvalidate();
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_net_percentage.postInvalidate();

				}
				else
				{
					_current_stock_net.setBackgroundColor(color);
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. _current_stock_net.postInvalidate();
					_current_stock_net_percentage
							.setBackgroundColor(color);
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _current_stock_net_percentage.postInvalidate();
				}
				break;
		}

	}

	/**
	 * @param strDate
	 *            such as: 20071011 Style such as: YYYYMMdd
	 * @param newStyle
	 *            such as: yy/MM/dd
	 * @return such as: 2007-10-11
	 */
	private String resetDateFormat(String strDate)
	{
		String result = strDate;
		if (strDate != null && strDate.length() >= 8)
		{
			String year = strDate.substring(0, 4);
			String month = strDate.substring(4, 6);
			String day = strDate.substring(6, 8);
			// Log.d("yymmdd",String.format("%s/%s/%s",year,month,day));
			result = String
					.format("%s/%s/%s", year.substring(2), month, day);
		}
		return result;
	}

	/*
	 * class ColorRefreshTask extends TimerTask { final static int DELAY_ONCE
	 * =200; final static int TOTAL_RUNTIME = 2400; final static int POWER_16_16
	 * = 16 * 16* 16 * 16 * 16 * 16; final static int INCREASE_ONCE = 0xff /
	 * (TOTAL_RUNTIME / DELAY_ONCE); int color; int id; int startTime; int
	 * alphaChannel;
	 *//**
		* @param color
		*            ( current background color)
		* @param id
		*            TableRow's id(user id)
		*/
	/*
	 * public ColorRefreshTask(int color, int id) { super(); Log.d("color",
	 * "ready to set color!"); this.color = color; this.id = id; this.startTime
	 * = 0; this.alphaChannel = 0; } public void run(){ int colorComm = color
	 * -0xff000000; //RGB color value; int currColor = 0; if(startTime <
	 * TOTAL_RUNTIME) { startTime += DELAY_ONCE; alphaChannel += INCREASE_ONCE;
	 * currColor = POWER_16_16 * alphaChannel + colorComm; // Log.d("color",
	 * Integer.toHexString(currColor)); sendMsg(currColor); if(_messageHandler
	 * == null || Thread.interrupted()) { cancel(); return; }
	 * _messageHandler.postDelayed(this,DELAY_ONCE); } else { sendMsg(currColor
	 * <= color ? color : 0 ); cancel(); } } public void startTimer(){
	 * if(_messageHandler == null || Thread.interrupted()) { return; }
	 * _messageHandler.postDelayed(this,DELAY_ONCE); } private void
	 * sendMsg(final int currColor){ final Runnable myUpdateResults = new
	 * Runnable() { public void run() { updateBackground( id, currColor); } };
	 * new Thread() { public void run() { if(_messageHandler == null ||
	 * Thread.interrupted()) { return; } _messageHandler.post(myUpdateResults);
	 * } }.start(); } public void stopTimer(){ this.cancel(); } }
	 */

	/**
	 * Setup a new 3D rotation on the container view.
	 * 
	 * @param position
	 *            the item that was clicked to show a picture, or -1 to show the
	 *            list
	 * @param start
	 *            the start angle at which the rotation must begin
	 * @param end
	 *            the end angle of the rotation
	 */
	private void applyRotation(int position, float start, float end)
	{
		// Find the center of the container
		final float centerX = _mContainer.getWidth() / 2.0f;
		final float centerY = _mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
				centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(position));

		_mContainer.startAnimation(rotation);
	}

	@Override
	public void onClick(View v)
	{
		if (v == _broker_queue_name)
		{
			applyRotation(-1, 180, 90);
		}
		if (v == _broker_queue_code)
		{
			applyRotation(0, 0, 90);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
	{
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.isCanceled())
		{
			if (_stockCode != null
					&& _stockCode.length() >= 1
					&& _current_stock_code.getText().toString().length() < 1)
				_current_stock_code.setText(_stockCode);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _current_stock_code.postInvalidate();
			_current_stock_code.clearFocus();
		}
		return false;
	}

	/**
	 * This class listens for the end of the first half of the animation. It
	 * then posts a new action that effectively swaps the views when the
	 * container is rotated 90 degrees and thus invisible.
	 */
	private final class DisplayNextView implements Animation.AnimationListener
	{
		private final int	mPosition;

		private DisplayNextView(int position)
		{
			mPosition = position;
		}

		public void onAnimationStart(Animation animation)
		{
		}

		public void onAnimationEnd(Animation animation)
		{
			_mContainer.post(new SwapViews(mPosition));
		}

		public void onAnimationRepeat(Animation animation)
		{
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation.
	 */
	private final class SwapViews implements Runnable
	{
		private final int	mPosition;

		public SwapViews(int position)
		{
			mPosition = position;
		}

		public void run()
		{
			final float centerX = _mContainer.getWidth() / 2.0f;
			final float centerY = _mContainer.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (mPosition > -1)
			{
				_broker_queue_code.setVisibility(View.GONE);
				_broker_queue_name.setVisibility(View.VISIBLE);
				_broker_queue_name.requestFocus();

				// rotation = new Rotate3dAnimation(90, 180, centerX, centerY,
				// 310.0f, false);
				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}
			else
			{
				_broker_queue_name.setVisibility(View.GONE);
				_broker_queue_code.setVisibility(View.VISIBLE);
				_broker_queue_code.requestFocus();

				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			_mContainer.startAnimation(rotation);
		}
	}

	private class CallbackHandlerOnIndex implements
		LightStreamerHandlerInterface
	{
		public void onUpdate(int itemPos, String itemName, UpdateInfo update)
		{
			if (_isInBackground)
			{
				return;
			}

			TDStockLog.d(TAG, "CallbackHandlerOnIndex works!");
			final Bundle bundle = new Bundle();
			bundle.putString(MESSAGE_KEY_INDEX_NAME, itemName);
			bundle.putString(IndexInfo.INDEXLAST,
					update.getNewValue(IndexInfo.INDEXLAST));
			bundle.putString(IndexInfo.INDEXNET,
					update.getNewValue(IndexInfo.INDEXNET));
			bundle.putString(IndexInfo.TURNOVER,
					update.getNewValue(IndexInfo.TURNOVER));
			bundle.putString(IndexInfo.INDEXNETPRECENTAGE,
					update.getNewValue(IndexInfo.INDEXNETPRECENTAGE));

			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					updateIndex(bundle);
				}
			};

			new Thread()
			{
				public void run()
				{
					_messageHandler.post(myUpdateResults);
				}
			}.start();

		}
	}

	private class CallbackHandlerOnStock implements
		LightStreamerHandlerInterface
	{
		private long	_last_stock_info_deal_with_time	= 1l;

		public CallbackHandlerOnStock()
		{
			_last_stock_info_deal_with_time = 1l;
		}

		public void onUpdate(final int itemPos, final String itemName,
				final UpdateInfo update)
		{
			/*
			 * Date now = new Date(); _cdr._cdrCounter = now.getTime() -
			 * _cdr._starttime.getTime(); //update the counter by using stream
			 */

			if (_isInBackground)
			{
				return;
			}
			if ((_last_stock_info_deal_with_time != 1l)
					&& (Math.abs(System.currentTimeMillis()
							- _last_stock_info_deal_with_time) < UPDATE_STOCK_INFO_INTERVAL))
			{
				TDStockLog.d(TAG,
						"so few time, do nothing (_last_stock_info_deal_with_time=)"
								+ _last_stock_info_deal_with_time);
				return; // so few time, do nothing to avoid ANR
			}
			// if(_last_stock_info_deal_with_stamp.getValue() != 1l &&
			// (Math.abs(System.currentTimeMillis()
			// -_last_stock_info_deal_with_stamp.getValue() ) <
			// UPDATE_STOCK_INFO_INTERVAL)) {
			// Log.d(TAG,
			// "so few time, do nothing (_last_stock_info_deal_with_time=)" +
			// _last_stock_info_deal_with_stamp.getValue());
			// return; //so few time, do nothing to avoid ANR
			// }
			// _last_stock_info_deal_with_stamp.setValue(
			// System.currentTimeMillis());
			// Log.d(TAG, "update timestamp:" +
			// _last_stock_info_deal_with_stamp.getValue() + ",Thread id=" +
			// Thread.currentThread().getId());

			/*
			 * if (_current_stock_code.getText().toString().length() > 0 &&
			 * !_current_stock_code.getText().toString().equals( itemName)
			 */if (!_stockCode.equals(itemName))
			{
				TDStockLog.d(TAG, "ItemName=" + itemName
						+ " and  current stock code: "
						+ _current_stock_code.getText().toString());
				return;
			}

			/*
			 * if(!itemName.equals(_current_stock_code.getText().toString())) {
			 * new Thread() { public void run() {
			 * //_messageHandler.post(myUpdateResults); _messageHandler.post(
			 * new Runnable() { public void run() {
			 * _current_stock_code.setText(itemName) ; // modified by haibo,
			 * 2011-06-20, no need to do so and it cause the anr.
			 * _current_stock_code.postInvalidate(); }); } } }.start(); }
			 */

			// Message msg = _messageHandler.obtainMessage();
			// msg.what = MESSAGE_HANDLE_ID_UPDATE_DATA_STOCK;
			final Bundle bundle = new Bundle();
			// bundle.putInt(MESSAGE_KEY_ID, Integer.parseInt(itemName, 10));
			for (int index = 0, len = StockInfo.SUBSCRIBE_FIELDS.length; index < len; index++)
			{
				bundle.putString(StockInfo.SUBSCRIBE_FIELDS[index], update
						.getNewValue(StockInfo.SUBSCRIBE_FIELDS[index]));
			}
			// msg.setData(bundle);
			// _messageHandler.sendMessage(msg);

			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{

					try
					{
						updateCurrentStockInfo(bundle);
					}
					catch (Exception e)
					{
						TDStockLog.e(
								TAG,
								e.getMessage() == null ? "exception in update current stock info!"
										: e.getMessage());
					}
				}
			};

			if (((ITDLApplication) getApplicationContext()).getDataMode() != CommonDefn.DataMode.Delay)
			{
				update_BID_QUEUE(
						update.getNewValue(StockInfo.BROKERQUEUEBIDSPREAD),
						_BID_LEFT_TEXTVIEWS, _BID_RIGHT_TEXTVIEWS);
				update_ASK_QUEUE(
						update.getNewValue(StockInfo.BROKERQUEUEASKSPREAD),
						_ASK_LEFT_TEXTVIEWS, _ASK_RIGHT_TEXTVIEWS);

				update_BID_QUEUE(
						update.getNewValue(StockInfo.BROKERQUEUEBIDSPREADNAME),
						_BID_LEFT_TEXTVIEWS_CH, _BID_RIGHT_TEXTVIEWS_CH);
				update_ASK_QUEUE(
						update.getNewValue(StockInfo.BROKERQUEUEASKSPREADNAME),
						_ASK_LEFT_TEXTVIEWS_CH, _ASK_RIGHT_TEXTVIEWS_CH);
			}

			new Thread()
			{
				public void run()
				{
					// _messageHandler.post(myUpdateResults);
					_messageHandler.post(myUpdateResults);
				}
			}.start();
		}
	}

	private class CallbackHandlerOnTimeServer implements
		LightStreamerHandlerInterface
	{
		public void onUpdate(int itemPos, String itemName,
				final UpdateInfo update)
		{
			if (_isInBackground)
			{
				return;
			}
			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					syncServerTimer(update
							.getNewValue(TimestampInfo.FIELD));
				}
			};

			new Thread()
			{
				public void run()
				{
					_messageHandler.post(myUpdateResults);
				}
			}.start();
		}
	}

	private class CallbackHandlerOnWorldIndex implements
		LightStreamerHandlerInterface
	{
		public void onUpdate(int itemPos, String itemName,
				final UpdateInfo update)
		{
			if (_isInBackground)
			{
				return;
			}
			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					updateWorldIndex(
							update.getNewValue(WorldIndexInfo.LAST),
							update.getNewValue(WorldIndexInfo.NET));
				}
			};

			new Thread()
			{
				public void run()
				{
					_messageHandler.post(myUpdateResults);
				}
			}.start();

		}
	}

	private class CallbackHandlerOnIndexFutures implements
		LightStreamerHandlerInterface
	{
		public void onUpdate(int itemPos, final String itemName,
				final UpdateInfo update)
		{
			if (_isInBackground)
			{
				return;
			}
			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					updateIndex_Futures(itemName,
							update.getNewValue(IndexFuturesInfo.LAST),
							update.getNewValue(IndexFuturesInfo.NET));
				}
			};

			new Thread()
			{
				public void run()
				{
					_messageHandler.post(myUpdateResults);
				}
			}.start();
		}

	}

	public synchronized void onConnectionEstablished()
	{
		/*
		 * try { if (_streamerTimeoutHandler != null) {
		 * _streamerTimeoutHandler.startCounter(_cdrHelper != null ?
		 * _cdrHelper._cdrCounter : 0); } _myClient = ((ITDLApplication)
		 * getApplicationContext()).getLightStreamerClient(); if
		 * (!((ITDLApplication)
		 * getApplicationContext()).isLightStreamerConnected()) { //
		 * _isSubscribed = false; // _subscrRefs.clear(); //haibo, do the clear
		 * action in on pause already. } String tmpCode =
		 * _prefsStockCode.getString(CommonDefn.PREFERENCE_STOCK_CODE, "1");
		 * final String codes[] = { Integer.toString(Integer.parseInt(tmpCode,
		 * 10)) }; if (!codes[0].equals(_stockCode)) { try { new
		 * SubscribeOthersTask().execute();
		 * dealwithNewStockCodeComingFromOtherPage(codes[0]); Log.e(TAG,
		 * "new stock code: " + codes[0]); } catch (Exception e) { Log.e(TAG,
		 * e.getMessage() == null ?
		 * "unknown exception happened while subscribe new stock code!" :
		 * ("subscribe new stock code" + e.getMessage())); } } else {
		 * ((ITDLApplication)
		 * CurrentStockInfoActivity.this.getApplicationContext
		 * ()).setCurrentStockName
		 * (_current_stock_chinese_short_name.getText().toString()); new
		 * SubscribeStockTask().execute(); new Thread() { public void run() {
		 * _stkTimeView.drawImmediately(); } }.start(); } new
		 * SubscribeOthersTask().execute(); ((ITDLApplication)
		 * getApplicationContext()).setResetCDR(false); } catch (Exception e) {
		 * //e.printStackTrace(); //handleLightStreamerException(e); Log.d(TAG,
		 * "error happened in the process of the subscription:" +
		 * (e.getMessage() == null ? "" : e.getMessage())); } finally {
		 * stopSunFlowBuy(); //moved by haibo, 2011-04-26 }
		 */
		String tmpCode = _prefsStockCode.getString(
				CommonDefn.PREFERENCE_STOCK_CODE, "1");
		if (!tmpCode.equals(_stockCode))
		{
			dealwithNewStockCodeComingFromOtherPage(tmpCode);
		}
		else
		{

			// unsubscribe the previous item first;
			if (!LightStreamerUnsubscribeItem(IDENTIFIER_0))
			{
				TDStockLog.d(TAG, "Lightstreamer error!");
			}

			subscribeStock();

			new Thread()
			{
				public void run()
				{
					_stkTimeView.drawImmediately();
				}
			}.start();

		}

		subscribeOthers();

		if (!((ITDLApplication) getApplicationContext()).isAdShowed())
		{
			((ITDLApplication) getApplicationContext()).setAdShowed(true);
			startAdAnim();
		}

	}

	private void subscribeStock(String... newStockCode)/*
														 * throws
														 * SubscrException,
														 * PushServerException,
														 * PushUserException,
														 * PushConnException
														 */
	{
		// _subscrRefs.clear();

		startSunflower();

		// --------------to avoid java.lang.NumberFormatException
		if (_stockCode == null || !TextUtils.isDigitsOnly(_stockCode))
		{
			_stockCode = "1";
		}

		String tmpCode = (newStockCode.length <= 0) ? Integer
				.toString(Integer.parseInt(_stockCode, 10))
				: newStockCode[0];
		// --------------to avoid java.lang.NumberFormatException
		((ITDLApplication) CurrentStockInfoActivity.this.getApplication())
				.setCurrentStockCode(tmpCode);

		if (_callBackHandlerOnStock == null)
		{
			_callBackHandlerOnStock = new CallbackHandlerOnStock();
		}

		LS_SubscriptionItem interestItem = new LS_SubscriptionItem(
				StockInfo.ADAPTER);
		interestItem.AddSubscribeItem(tmpCode);
		for (String field : StockInfo.SUBSCRIBE_FIELDS)
		{
			interestItem.AddSubscribeSchema(field);
		}

		/* IDENTIFIER_0 = LSGetUniqueID(); */
		if (LightStreamerSubscribeItem(IDENTIFIER_0, interestItem, this))
		{

		}

		/*
		 * _identityForsubscribedStock = subscribeItems(_myClient, tmpCodes,
		 * StockInfo.SUBSCRIBE_FIELDS, StockInfo.ADAPTER,
		 * _callBackHandlerOnStock);
		 * _subscrRefs.add(_identityForsubscribedStock);
		 */

	}

	private void handleBidAndAsk(TextView currentView, String value)
	{
		if (value == null || value.trim().length() < 1
				|| Long.parseLong(value) == 0)
		{
			currentView.setText("");
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. currentView.postInvalidate();
			return;
		}
		try
		{
			// modify by ouyangzhihui 2011-07-27
			long fieldValue = Long.parseLong(value);

			if (fieldValue >= 1000 && fieldValue < 1000 * 1000)
			{
				String tmp = StringUtils
						.roundDownFormatToAutoCharsRuleCutAllZero(
								String.valueOf(fieldValue / 1000.0d), 1);
				currentView.setText(tmp + CommonDefn.UNIT_K);

				// DT, 2011/02/01, bid and ask volume should have either 0 d.p.
				// or 1 d.p. only
				// String tmp = _formaterOnSacle2.format(fieldValue/1000.0d );
				// String tmp = _formaterOnSacle1.format(fieldValue / 1000.0d);
				/*
				 * String tmp = value.substring(0, value.length()-2); tmp = tmp
				 * + "00"; tmp = _formaterOnSacle1.format(Integer.parseInt(tmp)
				 * / 1000.0d); if (tmp.endsWith(".0")) {
				 * currentView.setText(String.valueOf(fieldValue / 1000) +
				 * CommonDefn.UNIT_K); } else { currentView.setText(tmp +
				 * CommonDefn.UNIT_K); }
				 */
			}
			else if (fieldValue >= 1000 * 1000
					&& fieldValue < 1000 * 1000 * 1000)
			{
				String tmp = StringUtils
						.roundDownFormatToAutoCharsRuleCutAllZero(
								String.valueOf(fieldValue / 1000000.0d),
								2);
				if (tmp.length() == 6)
				{
					tmp = StringUtils.roundDownFormatToFiveCharsRule(tmp);
				}
				currentView.setText(tmp + CommonDefn.UNIT_M);

				// DT, 2011/02/01, bid and ask volume should have either 0 d.p.
				// or 1 d.p. only
				// String tmp = _formaterOnSacle2.format(fieldValue/1000000.0d
				// );
				// String tmp = _formaterOnSacle2.format(fieldValue /
				// 1000000.00d); // modify by ouyangzhihui 2011-06-28
				// (_formaterOnSacle1)

				/*
				 * String tmp = value.substring(0, value.length()-4); tmp = tmp
				 * + "0000"; tmp =
				 * _formaterOnSacle2.format(Integer.parseInt(tmp) /
				 * 1000000.00d); if(tmp.length() == 6) { tmp = tmp.substring(0,
				 * tmp.length()-1); } if (tmp.endsWith(".00")) {
				 * currentView.setText(String.valueOf(fieldValue / 1000000) +
				 * CommonDefn.UNIT_M); } else { currentView.setText(tmp +
				 * CommonDefn.UNIT_M); }
				 */
			}
			else if (fieldValue >= 1000 * 1000 * 1000)
			{
				String tmp = StringUtils
						.roundDownFormatToAutoCharsRuleCutAllZero(
								String.valueOf(fieldValue / 1000000.0d),
								2);
				if (tmp.length() >= 6)
				{
					tmp = StringUtils.roundDownFormatToFiveCharsRule(tmp);
				}
				currentView.setText(tmp + CommonDefn.UNIT_B);

				// DT, 2011/02/01, bid and ask volume should have either 0 d.p.
				// or 1 d.p. only
				// String tmp =
				// _formaterOnSacle2.format(fieldValue/1000000000.0d );
				// String tmp = _formaterOnSacle1.format(fieldValue /
				// 1000000000.0d);

				/*
				 * String tmp = value.substring(0, value.length()-7); tmp = tmp
				 * + "0000000"; tmp =
				 * _formaterOnSacle2.format(Integer.parseInt(tmp) /
				 * 1000000000.00d); if (tmp.endsWith(".00")) {
				 * currentView.setText(String.valueOf(fieldValue / 1000000000) +
				 * CommonDefn.UNIT_B); } else { currentView.setText(tmp +
				 * CommonDefn.UNIT_B); }
				 */
			}
			else
			{
				currentView.setText(value);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	// modify by zor(ouyangzhihui)
	private void handleTranCNT(TextView currentView, String value,
			String defaultValue)
	{
		// modify by zor(ouyangzhihui) --start
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			currentView.setText(defaultValue);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. currentView.postInvalidate();
			return;
		}
		if (value == null || value.trim().length() < 1
				|| Integer.parseInt(value) == 0)
		{
			currentView.setText("(0)"); // modify by zor(ouyangzhihui)
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. currentView.postInvalidate();
			return;
		}
		// modify by zor(ouyangzhihui) --end
		currentView.setText(String.format("(%s)", value));
		// modified by haibo, 2011-06-20, no need to do so and it cause the anr.
		// currentView.postInvalidate();
	}

	private void handleTradeticker(final TextFitTextView[] txtView,
			String[] value)
	{
		// final int trade_len = 6;

		TDStockLog.d(TAG, String.format(" tradeTicker:  %d",
				value == null ? 0 : value.length));

		if (value == null)
		{
			/*
			 * txtView.setText(""); txtView.postInvalidate();
			 */// keep the old value
			return;
		}
		else
		{

			StringBuffer values = new StringBuffer();
			for (String str : value)
			{
				values.append(str).append(",");
			}

			TDStockLog.d(TAG,
					String.format(" value :  %s", values.toString()));

			if (value.length >= 4)
			{
				if (value[0].length() >= 3)
				{
					String time = "";
					if (value[0].length() >= 4) // i.e. 10:09
					{
						time = value[0].substring(0, 2) + ":"
								+ value[0].substring(2, 4);
					}
					else
					{
						// i.e. 951
						time = value[0].substring(0, 1) + ":"
								+ value[0].substring(1, 3);
					}
					double theTrade;
					try
					{
						theTrade = Double.parseDouble(value[2]);
					}
					catch (NumberFormatException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
						return;
					}
					String trade = null;
					StringBuffer buff = new StringBuffer();
					if (theTrade >= 1000 * 1000 * 1000)
					{
						theTrade = theTrade / (1000 * 1000 * 1000);
						String tmp = _formaterOnSacle1.format(theTrade);
						if (tmp.endsWith(".0"))
						{
							tmp = String.valueOf((int) theTrade);
						}
						/*
						 * int addSpaceTimes = trade_len - tmp.length(); for(int
						 * index = 0; index < addSpaceTimes; index++) {
						 * buff.append("&nbsp;"); }
						 */

						buff.append(tmp).append(CommonDefn.UNIT_B);
						trade = buff.toString();
					}
					else if (theTrade >= 1000 * 1000)
					{
						theTrade = theTrade / (1000 * 1000);
						String tmp = _formaterOnSacle1.format(theTrade);
						if (tmp.endsWith(".0"))
						{
							tmp = String.valueOf((int) theTrade);
						}
						/*
						 * int addSpaceTimes = trade_len - tmp.length(); for(int
						 * index = 0; index < addSpaceTimes; index++) {
						 * buff.append("&nbsp;"); }
						 */

						buff.append(tmp).append(CommonDefn.UNIT_M);
						trade = buff.toString();
					}
					else if (theTrade >= 1000)
					{
						theTrade = theTrade / 1000;
						String tmp = _formaterOnSacle1.format(theTrade);
						if (tmp.endsWith(".0"))
						{
							tmp = String.valueOf((int) theTrade);
						}
						/*
						 * int addSpaceTimes = trade_len - tmp.length(); for(int
						 * index = 0; index < addSpaceTimes; index++) {
						 * buff.append("&nbsp;"); }
						 */

						buff.append(tmp).append(CommonDefn.UNIT_K);
						trade = buff.toString();
					}
					else
					{
						// int addSpaceTimes = trade_len -
						// String.valueOf((int)theTrade).length();
						/*
						 * for(int index = 0; index < addSpaceTimes; index++) {
						 * buff.append("&nbsp;"); }
						 */
						buff.append((int) theTrade);
						trade = buff.toString();
					}
					String price = value[3];

					String others = "";
					if (value.length >= 6 && value[5] != null)
					{
						others = value[5];
					}
					if (value.length >= 5 && value[4] != null)
					{
						time += value[4];
					}

					// String htmlContent = new
					// StringBuffer().append("<span><font size='200%' color='white' >").append(time)
					// .append(" </font>&nbsp; <font size='200%' color='white' >").append(trade)
					// .append(" </font>&nbsp;<font size='200%' color='white' >").append(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,price))
					// .append("</font>&nbsp; <font size='200%' color='white' >").append(others)
					// .append(" </font> </span>")
					// .toString();

					// String.format("<span><font size='3' color='white' > %s </font> &nbsp; &nbsp; <font size='2' color='white' > %s </font> &nbsp; &nbsp;<font size='3' color='white' > %s </font><font size='3' color='white' > %s </font> </span>",
					// time, trade,
					// StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,price),
					// others);

					final String time_value = time;
					final String trade_value = trade;
					final String price_value = StringUtils.FormatNumber(
							StringUtils.ITDLNumber.STOCKPRICE, price);
					final String other_value = others;

					final Runnable job = new Runnable()
					{
						public void run()
						{

							txtView[0].setText(time_value);
							// modified by haibo, 2011-06-20, no need to do so
							// and it cause the anr.
							// txtView[0].postInvalidate();
							txtView[1].setText(trade_value);
							// modified by haibo, 2011-06-20, no need to do so
							// and it cause the anr.
							// txtView[1].postInvalidate();
							txtView[2].setText(price_value);
							// modified by haibo, 2011-06-20, no need to do so
							// and it cause the anr.
							// txtView[2].postInvalidate();
							txtView[3].setText(other_value);
							// modified by haibo, 2011-06-20, no need to do so
							// and it cause the anr.
							// txtView[3].postInvalidate();
						}
					};

					new Thread()
					{
						public void run()
						{
							if (_messageHandler != null)
								_messageHandler.post(job);
						}
					}.start(); // modified by haibo, 2011-07-27, to avoid anr

				}

			}

		}
	}

	private class ChartClickHandler extends DefaultClickHandler
	{
		public ChartClickHandler(Context context)
		{
			super(context);
		}

		@Override
		protected void onDefaultAction()
		{
			_chart_mask.setText("轉動以瀏覽圖表");
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _chart_mask.postInvalidate();

			final Runnable myUpdateResults = new Runnable()
			{
				public void run()
				{
					_chart_mask.setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr. _chart_mask.postInvalidate();
				}
			};

			new Thread()
			{
				public void run()
				{
					_messageHandler.postDelayed(myUpdateResults, 5000);
					// _messageHandler.post(myUpdateResults);
				}
			}.start();

		}
	}

	private class AddStockClickHandler extends DefaultClickHandler
	{
		public AddStockClickHandler(Context context)
		{
			super(context);
		}

		@Override
		protected void onDefaultAction()
		{
			if (container_input != null)
			{
				if (container_input.getVisibility() != View.GONE)
				{
					new CustomizeDialog(getMyOwnContext(), "", "請先按鍵確認股號!")
							.show();
					return;
				}
			}

			String stockCode = _current_stock_code.getText().toString();
			if (stockCode.length() < 1)
			{
				if (_stockCode.length() < 1)
				{
					// should fill the stock code first;
					return;
				}
				else
					stockCode = _stockCode;
			}
			
			if (((ITDLApplication) getApplicationContext()).getModeType() == CommonDefn.ModeType.DELARY)
			{
				DBHelper dbHelper = new DBHelper(CurrentStockInfoActivity.this);
				try
				{
					
					int customerId = 1;
					// 判断监察表中是否存在
					if (dbHelper.isSubscribeItemExist(customerId,
							stockCode, StockInfo.ADAPTER))
					{
						new CustomizeDialog(getMyOwnContext(), "",
								getResources().getString(
										R.string.monitor_exist_stock))
								.show();
						/*
						 * new
						 * AlertDialog.Builder(CurrentStockInfoActivity.this.
						 * getMyOwnContext
						 * ()).setTitle(getResources().getString(R
						 * .string.info)).setMessage(
						 * getResources().getString(R.
						 * string.monitor_exist_stock)
						 * ).setIcon(getResources().getDrawable
						 * (R.drawable.help_menu_icon)).setPositiveButton(
						 * getResources().getString(R.string.ok), new
						 * DialogInterface.OnClickListener(){public void
						 * onClick(DialogInterface dialoginterface, int
						 * i){}}).show();
						 */
					}
					else if (dbHelper.isFullWithItemInMonitor(customerId))
					{
						new CustomizeDialog(
								getMyOwnContext(),
								"",
								getResources()
										.getString(
												R.string.monitor_is_full_with_items))
								.show();
						/*
						 * new AlertDialog.Builder(
						 * ForeignExchangeActivity.thisgetMyOwnContext
						 * ()).setTitle(getResources().getString(R.string.info))
						 * .setMessage(getResources().getString(R.string.
						 * monitor_is_full_with_items))
						 * .setIcon(getResources().getDrawable
						 * (R.drawable.help_menu_icon))
						 * .setPositiveButton(getResources
						 * ().getString(R.string.ok), new
						 * DialogInterface.OnClickListener(){public void
						 * onClick(DialogInterface dialoginterface,int
						 * i){}}).show();
						 */
					}
					else
					{
						long result = dbHelper.insertSubscribeItem(
								customerId, stockCode,
								StockInfo.ADAPTER,
								StockInfo.STOCKCHISHORTNAME,
								StockInfo.NOMINAL, StockInfo.NET,
								StockInfo.NETPERCENTAGE);
						if (result > 0)
						{
							String temp = _current_stock_chinese_short_name
									.getText().toString()
									+ " "
									+ stockCode;
							// Log.d("test",
							// CommonDefn.BookMarkType.stock.getBookMarkType()+"----->"+_current_stock_chinese_short_name.getText().toString()+"  "+stockCode);
							startAnimat(temp);
							TDStockLog.d(TAG, "insert result:" + result);
							TDStockLog.d(TAG, "insert result:" + result);
/*							new CustomizeDialog(getMyOwnContext(), "",
									getResources().getString(
											R.string.monitor_add_to))
									.show();*/
						}
					}
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
					TDStockLog.d(
							TAG,
							"insert result:" + e.getMessage() == null ? "unknown exception!"
									: e.getMessage());
				}
				finally
				{
					dbHelper.cleanup();
				}
			}
			// 非延迟模式
			else
			{
				new SaveBookMarkAsyncTask(stockCode,
						CommonDefn.BookMarkType.stock.getBookMarkType(),
						CurrentStockInfoActivity.this,
						MonitorUtil.getInstance(),
						_current_stock_chinese_short_name.getText()
								.toString() + " " + stockCode)
						.execute();
			}
		}
	}

	private void dealWithNewStockCodeComingFromEditor()
	{
		TDStockLog.d(TAG, "ready to deal with new stock code!");
		_current_stock_nominal.setTag(null);
		resetTradeTicker();
		if (_isShowingStreamerTimeoutLabel)
		{
			TDStockLog.d(TAG, "ready to deal with streamer timeout label!");
			performClickStreamerTimeoutLabel();
		}
		/*
		 * if (_streamerTimeoutHandler != null) {
		 * _streamerTimeoutHandler.startCounter(_cdrHelper != null ?
		 * _cdrHelper._cdrCounter : 0 ); //restart counter; }
		 */
		String s = _current_stock_code.getText().toString().trim();
		if ("".equals(s) || Integer.parseInt(s) <= 0)
		{
			TDStockLog.d(TAG, " stock code is empty !");
			try
			{
				if (_entryErrordialog == null)
				{
					_entryErrordialog = new CustomizeDialog(
							getMyOwnContext(), "", getResources()
									.getString(R.string.entry_error))
					{
						@Override
						public void onClick(View v)
						{
							/** When OK Button is clicked, dismiss the dialog */
							if (v == okButton)
							{
								dismiss();
								if (_stockCode != null
										&& _stockCode.length() >= 1)
								{
									_current_stock_code
											.setText(_stockCode);
									// modified by haibo, 2011-06-20, no need to
									// do so and it cause the anr.
									// _current_stock_code.postInvalidate();
									_current_stock_code.clearFocus();
								}
								Thread.yield();
								TDStockLog.d(TAG, " reset text !");
							}

						}
					};
				}

				_entryErrordialog.show();
			}
			catch (Exception e)
			{
				TDStockLog.e(
						TAG,
						e.getMessage() == null ? "unknow exception happened when stock code is empty!"
								: "exception: " + e.getMessage());
			}
			/*
			 * finally { stopSunFlowBuy(); }
			 */
			return;
		}

		if (!s.equals(_stockCode) && (!s.equals("")))
		{
			// startSunFlowBuy();
			if (!s.toString().equals(_lastStockCode))
			{
				_lastStockCode = _stockCode;
				_isNewStock = true;
			}

			// if( (_stockCode != null) && !s.equals(_stockCode) &&
			// (!s.toString().equals(""))) {
			try
			{
				_stockCode = String.valueOf(Integer.parseInt(s, 10));
				((ITDLApplication) CurrentStockInfoActivity.this
						.getApplication())
						.setCurrentStockCode(_stockCode);
			}
			catch (NumberFormatException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return;
			}
			_prefsStockCode = getSharedPreferences(
					CommonDefn.SYSTEM_CURRENT_SETTING,
					Context.MODE_PRIVATE);
			_prefsStockCode
					.edit()
					.putString(CommonDefn.PREFERENCE_STOCK_CODE,
							_stockCode).commit();

			/*
			 * Intent notifyChanges = new
			 * Intent(CommonDefn.RECEIVER_ITEM_CODE_CHANGE, null);
			 * sendBroadcast(notifyChanges);
			 */

			new Thread()
			{
				public void run()
				{
					_stkTimeView.drawImmediately();
				}
			}.start();

			try
			{
				/*
				 * _myClient = ((ITDLApplication)
				 * getApplicationContext()).getLightStreamerClient(); if
				 * (_identityForsubscribedStock != null) {
				 * _myClient.unsubscribeTable(_identityForsubscribedStock);
				 * //must get the value item which index is 0
				 * _subscrRefs.remove(_identityForsubscribedStock); }
				 * _subscrRefs.clear(); //only the first one is important!
				 */
				if (IDENTIFIER_0 != null || IDENTIFIER_0.length() >= 1)
				{
					if (!LightStreamerUnsubscribeItem(IDENTIFIER_0))
					{
						new CustomizeDialog(
								CurrentStockInfoActivity.this
										.getMyOwnContext(),
								getResources().getString(R.string.info),
								getResources()
										.getString(
												R.string.networking_disconnect_tips),
								getResources().getString(R.string.ok))
						{
							@Override
							public void onClick(View v)
							{
								if (v == okButton)
								{
									if (SystemInfo
											.isNetworkingConnected(CurrentStockInfoActivity.this
													.getMyOwnContext()))
									{
										connectLightStreamerExt(CurrentStockInfoActivity.this
												.getMyOwnContext());
									}
									this.dismiss();
								}
							}
						}.show();

						return;
					}
					// Try to resume all data, HSI, time and etc..
					LS_ResumeAllItem();
				}

				try
				{
					Thread.sleep(500);
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}

				/*
				 * if (_callBackHandlerOnStock == null) {
				 * _callBackHandlerOnStock = new CallbackHandlerOnStock(); }
				 * _identityForsubscribedStock = subscribeItems(_myClient, new
				 * String[] { _stockCode }, StockInfo.SUBSCRIBE_FIELDS,
				 * StockInfo.ADAPTER, _callBackHandlerOnStock);
				 * _subscrRefs.add(0, _identityForsubscribedStock);
				 */

				subscribeStock(_stockCode);
			}
			catch (Exception e)
			{
				((ITDLApplication) getApplicationContext())
						.setLightStreamerConnected(false);
				e.printStackTrace();
				TDStockLog.e(
						TAG,
						e.getMessage() == null ? " unknown exception happened!"
								: e.getMessage());

				try
				{
					new CustomizeDialog(
							CurrentStockInfoActivity.this
									.getMyOwnContext(),
							getResources().getString(R.string.info),
							getResources()
									.getString(
											R.string.networking_disconnect_tips),
							getResources().getString(R.string.ok))
					{
						@Override
						public void onClick(View v)
						{
							if (v == okButton)
							{
								if (SystemInfo
										.isNetworkingConnected(CurrentStockInfoActivity.this
												.getMyOwnContext()))
								{
									((ITDLApplication) getApplicationContext())
											.setLightStreamerConnected(false);
									connectLightStreamerExt(CurrentStockInfoActivity.this
											.getMyOwnContext());

								}
								this.dismiss();
							}
						}
					}.show();
					/*
					 * newAlertDialog.Builder(CurrentStockInfoActivity.this.
					 * getMyOwnContext
					 * ()).setTitle(getResources().getString(R.string
					 * .info)).setMessage(
					 * getResources().getString(R.string.networking_disconnect_tips
					 * )).setIcon(getResources().getDrawable(R.drawable.
					 * help_menu_icon)).setPositiveButton(
					 * getResources().getString(R.string.ok), new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialoginterface, int i) { if
					 * (SystemInfo
					 * .isNetworkingConnected(CurrentStockInfoActivity
					 * .this.getMyOwnContext())) {
					 * connectLightStreamerEx(CurrentStockInfoActivity
					 * .this.getMyOwnContext()); } } }).show();
					 */
				}
				catch (Exception e1)
				{
					e1.printStackTrace();
				}
			}
		}

	}

	private void dealwithNewStockCodeComingFromOtherPage(String newCode)
	{
		TDStockLog.d(TAG, "ready to deal with new stock code!");
		_current_stock_nominal.setTag(null);
		_lastStockCode = _current_stock_code.getText().toString();
		_current_stock_code.setText(newCode);

		/*
		 * try { _myClient = ((ITDLApplication)
		 * getApplicationContext()).getLightStreamerClient(); if
		 * (_identityForsubscribedStock != null) {
		 * _myClient.unsubscribeTable(_identityForsubscribedStock);
		 * _subscrRefs.remove(_identityForsubscribedStock); } } catch (Exception
		 * e1) { if (_identityForsubscribedStock != null) { try {
		 * _myClient.forceUnsubscribeTable(_identityForsubscribedStock);
		 * _subscrRefs.remove(_identityForsubscribedStock); } catch (Exception
		 * e) { Log.e(TAG, "failed to unsubscribe item on the second time!");
		 * Log.e(TAG, e.getMessage() == null ?
		 * "unkonw exception in dealwithNewStockCodeComingFromOtherPage" :
		 * e.getMessage()); } } Log.e(TAG, "failed to unsubscribe item : " +
		 * _lastStockCode); Log.e(TAG, e1.getMessage() == null ?
		 * "unkonw exception in dealwithNewStockCodeComingFromOtherPage" :
		 * e1.getMessage()); e1.printStackTrace(); }
		 */

		_stockCode = newCode;
		((ITDLApplication) CurrentStockInfoActivity.this.getApplication())
				.setCurrentStockCode(_stockCode);
		resetTradeTicker();
		if (_isShowingStreamerTimeoutLabel)
		{
			TDStockLog.d(TAG, "ready to deal with streamer timeout label!");
			performClickStreamerTimeoutLabel();
		}

		/*
		 * if (_streamerTimeoutHandler != null) {
		 * _streamerTimeoutHandler.startCounter(_cdrHelper != null ?
		 * _cdrHelper._cdrCounter : 0); //restart counter; }
		 */

		new Thread()
		{
			public void run()
			{
				_stkTimeView.drawImmediately();
			}
		}.start();

		try
		{
			// startSunFlowBuy();
			try
			{
				Thread.sleep(500);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}

			if (_callBackHandlerOnStock == null)
			{
				_callBackHandlerOnStock = new CallbackHandlerOnStock();
			}

			/*
			 * _identityForsubscribedStock = subscribeItems(_myClient, new
			 * String[] { newCode }, StockInfo.SUBSCRIBE_FIELDS,
			 * StockInfo.ADAPTER, _callBackHandlerOnStock); _subscrRefs.add(0,
			 * _identityForsubscribedStock);
			 */

			subscribeStock(newCode);

		}
		catch (Exception e)
		{
			e.printStackTrace();
			TDStockLog.e(
					TAG,
					e.getMessage() == null ? " unknown exception happened!"
							: e.getMessage());

			new CustomizeDialog(
					CurrentStockInfoActivity.this.getMyOwnContext(),
					getResources().getString(R.string.info),
					getResources().getString(
							R.string.networking_disconnect_tips)
							+ (e.getMessage() == null ? "" : e
									.getMessage()), getResources()
							.getString(R.string.ok))
			{
				@Override
				public void onClick(View v)
				{
					if (v == okButton)
					{
						if (SystemInfo
								.isNetworkingConnected(CurrentStockInfoActivity.this
										.getMyOwnContext()))
						{
							// ((ITDLApplication)
							// getApplicationContext()).setLightStreamerConnected(false);
							connectLightStreamerExt(CurrentStockInfoActivity.this
									.getMyOwnContext());

						}
						dismiss();
					}
				}
			}.show();

		}
		/*
		 * finally { stopSunFlowBuy(); }
		 */
	}

	// 交易记录，处理展示
	private void initTradetickerView()
	{
		final String[] tags = { "ticker_time", "ticker_trade",
				"ticker_price", "ticker_type" };
		final int[] resourceIds = { R.id.stock_tradeticker_01,
				R.id.stock_tradeticker_02, R.id.stock_tradeticker_03,
				R.id.stock_tradeticker_04, R.id.stock_tradeticker_05 };
		for (int index = 0; index < resourceIds.length; index++)
		{
			ViewGroup container = (ViewGroup) findViewById(resourceIds[index]);
			_tradeticker_textviews[index] = new TextFitTextView[tags.length];
			for (int item = 0; item < tags.length; item++)
			{
				_tradeticker_textviews[index][item] = (TextFitTextView) container
						.findViewWithTag(tags[item]);
				_tradeticker_textviews[index][item].setMinTextSize(10);
				_tradeticker_textviews[index][item].setMaxTextSize(17);
				_tradeticker_textviews[index][item].setSingleLine(true);
				if (item == 0)
				{
					_tradeticker_textviews[index][item].setTextSize(13);
				}
				else if (item == 1)
				{
					_tradeticker_textviews[index][item].setTextSize(17);
				}
				if (item == 2)
				{
					_tradeticker_textviews[index][item].setTextSize(17);
				}
				if (item == 3)
				{
					_tradeticker_textviews[index][item].setTextSize(17);
				}
			}

		}

	}

	protected Context getMyOwnContext()
	{
		// return _context;
		return getParent();
	}

	private void resetFieldValue(boolean isWarrant, final Bundle fromMsg)
	{

		if (!isWarrant)
		{
			try
			{
				_current_stock_ex_ymd.setText(resetDateFormat(fromMsg
						.getString(StockInfo.EXYMD)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_ex_ymd.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_ex_ymd
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_ex_ymd.postInvalidate();
			}
			// --01

			try
			{
				_current_stock_div_ymd.setText(resetDateFormat(fromMsg
						.getString(StockInfo.DIVYMD)));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_div_ymd.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_div_ymd
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_div_ymd.postInvalidate();
			} // --02

			double nominal = 0.00d;
			try
			{
				nominal = Double.parseDouble(fromMsg
						.getString(StockInfo.NOMINAL));
			}
			catch (Exception e)
			{
			}

			double divValue = 0.00d;
			try
			{
				divValue = Double.parseDouble(fromMsg
						.getString(StockInfo.DIVVALUE));
			}
			catch (Exception e)
			{

			}

			double dividendPaid = 0.00d;
			try
			{
				dividendPaid = Double.parseDouble(fromMsg
						.getString(StockInfo.DIVIDENDPAID));
			}
			catch (Exception e)
			{

			}

			// DT, 2011/01/14, format to 0 d.p., need to be the same as iPhone
			// app
			// _current_stock_div_value.setText(Math.abs(divValue) <= 0.000001d
			// ? CommonDefn.DEFAULT_FIELD_VALUE : String.valueOf(divValue) +
			// getResources().getString(R.string.cent) );
			try
			{
				/* // modify by zor(ouyangzhihui) 2011-08-12 --start */
				String tmp = Math.abs(divValue) <= 0.000001d ? CommonDefn.DEFAULT_FIELD_VALUE
						: String.valueOf(divValue);
				if (Double.parseDouble(tmp) < 100)
				{
					// tmp = StringUtils.formatToSixCharsRuleWithoutSign(tmp) +
					// getResources().getString(R.string.cent);
					tmp = StringUtils.roundDownFormatToSixCharsRule(tmp)
							+ getResources().getString(R.string.cent);
				}
				else
				{
					// tmp = String.valueOf((int) Double.parseDouble(tmp));
					// tmp = tmp.substring(0, tmp.length() - 2) + "." +
					// tmp.substring(tmp.length() - 2) +
					// getResources().getString(R.string.yuan);
					tmp = String
							.valueOf(Double.parseDouble(tmp) / 100.00d);
					tmp = StringUtils.roundDownFormatToAutoCharsRule(tmp,
							2, true)
							+ getResources().getString(R.string.yuan);
				}
				/* // modify by zor(ouyangzhihui) 2011-08-12 --end */
				_current_stock_div_value.setText(tmp);

				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_div_value.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_div_value
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_div_value.postInvalidate(); // --03
			}

			// DT, 2011/01/14, shows "---" if not available, need to be the same
			// as iPhone app
			// TODO: _current_stock_rate_of_return is too different from web
			// site www.aastocks.com, if the formular correct?
			// _current_stock_rate_of_return.setText( (Math.abs(divValue) <=
			// 0.000001d || Math.abs(nominal) <= 0.000001d ) ?
			// CommonDefn.DEFAULT_FIELD_VALUE : _formaterOnSacle2.format(
			// divValue/ nominal * 100) + "%");
			try
			{
				// _current_stock_rate_of_return.setText( (Math.abs(divValue) <=
				// 0.000001d || Math.abs(nominal) <= 0.000001d ) ?
				// CommonDefn.DEFAULT_FIELD_VALUE : _formaterOnSacle2.format(
				// divValue/ nominal * 100) + "%");

				_current_stock_rate_of_return
						.setText((Math.abs(dividendPaid) <= 0.000001d || Math
								.abs(nominal) <= 0.000001d) ? CommonDefn.DEFAULT_FIELD_VALUE
								: StringUtils
										.roundDownFormatToSixCharsRule(dividendPaid
												/ nominal
												* 100
												+ "")); // modify
				// by
				// zor(ouyangzhihui)
				// 2011-08-12

				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_rate_of_return.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_rate_of_return
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_rate_of_return.postInvalidate(); // --04
			}

			double profitpershare = 0.00d;
			try
			{
				profitpershare = Double.parseDouble(fromMsg
						.getString(StockInfo.PROFITPERSHARE));
				// modify by zor(ouyangzhihui) 2011-08-12
				String profitPershareStr = Math.abs(profitpershare) <= 0.000001d ? CommonDefn.DEFAULT_FIELD_VALUE
						: StringUtils
								.roundDownFormatToSixCharsRule(String
										.valueOf(profitpershare));

				// DT, 2011/01/14, format to 4 d.p., need to be the same as
				// iPhone app
				// _current_stock_profitpershare.setText(StringUtils.FormatNumber(StringUtils.ITDLNumber.STOCKPRICE,
				// profitPershareStr));

				_current_stock_profitpershare.setText(profitPershareStr);

				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_profitpershare.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_profitpershare
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_profitpershare.postInvalidate(); // --05
			}

			String peStr = (Math.abs(profitpershare) <= 0.000001d || Math
					.abs(nominal) <= 0.000001d) ? CommonDefn.DEFAULT_FIELD_VALUE
					: String.valueOf((nominal / profitpershare));
			try
			{
				_current_stock_pe.setText(StringUtils
						.roundDownFormatToAutoCharsRule(peStr, 4, true)); // modify
				// by
				// zor(ouyangzhihui)
				// 2011-08-12
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_pe.postInvalidate();
			}
			catch (Exception e)
			{
				_current_stock_pe.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_current_stock_pe.postInvalidate(); // --06
			}

			// by ouyangzhihui move to update all
			/*
			 * try {
			 * _current_stock_currency.setText(fromMsg.getString(StockInfo.
			 * CURRENCYCODE) == null ? CommonDefn.DEFAULT_FIELD_VALUE :
			 * fromMsg.getString(StockInfo.CURRENCYCODE)); // modified by haibo,
			 * 2011-06-20, no need to do so and it cause the anr.
			 * _current_stock_currency.postInvalidate(); } catch (Exception e) {
			 * _current_stock_currency.setText(CommonDefn.DEFAULT_FIELD_VALUE);
			 * // modified by haibo, 2011-06-20, no need to do so and it cause
			 * the anr. _current_stock_currency.postInvalidate(); }
			 */
		}
		else
		{

			try
			{
				_field_value_4ReplaceMent[0]
						.setText(StringUtils.formatToDp(
								fromMsg.getString(StockInfo.RATIO), 3));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[0].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[0]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[0].postInvalidate();
			}

			try
			{
				String expDate_src = fromMsg.getString(StockInfo.EXPDATE);
				String expDate_dest = expDate_src.substring(2, 4) + "/"
						+ expDate_src.substring(5, 7) + "/"
						+ expDate_src.substring(8, 10);
				_field_value_4ReplaceMent[1].setText(expDate_dest);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[1].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[1]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[1].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[2].setText(fromMsg
						.getString(StockInfo.EXERPRICE));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[2].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[2]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[2].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[3].setText(fromMsg
						.getString(StockInfo.CALLPRICE));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[3].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[3]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[3].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[4].setText(fromMsg
						.getString(StockInfo.PREMIUM));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[4].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[4]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[4].postInvalidate();
			}

			try
			{
				_field_value_4ReplaceMent[5].setText(fromMsg
						.getString(StockInfo.PERCENTOUT));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_value_4ReplaceMent[5].postInvalidate();
			}
			catch (Exception e)
			{
				_field_value_4ReplaceMent[5]
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_value_4ReplaceMent[5].postInvalidate();
			}

			try
			{
				_field_current_stock_call_put.setText("P"
						.equalsIgnoreCase(fromMsg
								.getString(StockInfo.CALLPUT)) ? "Put輪"
						: "Call輪");
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_current_stock_call_put.postInvalidate();
			}
			catch (Exception e)
			{
				_field_current_stock_call_put
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_current_stock_call_put.postInvalidate();
			}

			try
			{
				_field_current_stock_gearing.setText(fromMsg
						.getString(StockInfo.GEARING));
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _field_current_stock_gearing.postInvalidate();
			}
			catch (Exception e)
			{
				_field_current_stock_gearing
						.setText(CommonDefn.DEFAULT_FIELD_VALUE);
				_field_current_stock_gearing.postInvalidate();
			}

		}

	}

	private void resetLayoutByState(boolean isWarrant)
	{
		if (_isWarrant == isWarrant || _rowForWarrant == null)
		{
			return;
		}

		_isWarrant = isWarrant;
		if (isWarrant)
		{
			_rowForWarrant.setVisibility(View.VISIBLE);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _rowForWarrant.postInvalidate();
			_label4ReplaceMent[0].setText(_res4ReplaceMent[1][0]);
			_label4ReplaceMent[1].setText(_res4ReplaceMent[1][1]);
			_label4ReplaceMent[2].setText(_res4ReplaceMent[1][2]);
			_label4ReplaceMent[3].setText(_res4ReplaceMent[1][3]);
			_label4ReplaceMent[4].setText(_res4ReplaceMent[1][4]);
			_label4ReplaceMent[5].setText(_res4ReplaceMent[1][5]);

			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[0].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[1].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[2].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[3].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[4].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[5].postInvalidate();
		}
		else
		{
			_rowForWarrant.setVisibility(View.GONE);
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _rowForWarrant.postInvalidate();

			_label4ReplaceMent[0].setText(_res4ReplaceMent[0][0]);
			_label4ReplaceMent[1].setText(_res4ReplaceMent[0][1]);
			_label4ReplaceMent[2].setText(_res4ReplaceMent[0][2]);
			_label4ReplaceMent[3].setText(_res4ReplaceMent[0][3]);
			_label4ReplaceMent[4].setText(_res4ReplaceMent[0][4]);
			_label4ReplaceMent[5].setText(_res4ReplaceMent[0][5]);

			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[0].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[1].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[2].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[3].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[4].postInvalidate();
			// modified by haibo, 2011-06-20, no need to do so and it cause the
			// anr. _label4ReplaceMent[5].postInvalidate();

		}

	}

	/*
	 * private void registerReceiver(Context context) { _sessionExpiredListe
	 * nerReceiver = new BroadcastReceiver() {
	 * 
	 * @Override public void onReceive(Context context, Intent intent) {
	 * Log.d(TAG, " received  session expired message,  starting to handle it");
	 * new Thread() {
	 * 
	 * @Override public void run() { String[] auth_info =
	 * isAuthComingFromActivationCode() ? new ActivationCodeAuth(
	 * getDeviceId(),getActivationCode()).getAuthentication() : new
	 * Authentication(getUser(), getPwd(),getDeviceId()).getAuthentication();
	 * //----cache session info----
	 * ((ITDLApplication)getApplicationContext()).setSessionAccount
	 * (auth_info[0]);
	 * ((ITDLApplication)getApplicationContext()).setSessionToken(auth_info[1]);
	 * //----cache session info---- Log.d(TAG,
	 * " update cache session sucessfully!"); } }.start(); } }; IntentFilter
	 * filter = new IntentFilter(CommonDefn.RECEIVER_SESSION_EXPIRED);
	 * context.registerReceiver(_sessionExpiredListenerReceiver, filter); }
	 */

	// private class SubscriptionTask extends AsyncTask<String, Void, Void> {
	//
	// @Override
	// protected Void doInBackground(String... params) {
	// onConnectionEstablished();
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result) {
	// super.onPostExecute(result);
	// }
	//
	// }

	@Override
	protected void onDestroy()
	{
		TDStockLog.e(TAG, "CurrentStockInfoActivity is dead!");
		/*
		 * if(_stkTimeView != null) {
		 * if(_stkTimeView._itemCodeChangeListenerReceiver != null) { try {
		 * this.
		 * unregisterReceiver(_stkTimeView._itemCodeChangeListenerReceiver); }
		 * catch(Exception e) { Log.e(TAG,
		 * "failed to unregisterReceiver:  _itemCodeChangeListenerReceiver! ");
		 * } } _stkTimeView = null; }
		 */

		/* Andy */
		// if (_streamerTimeoutHandler != null)
		// {
		// _streamerTimeoutHandler.killCounter();
		// _streamerTimeoutHandler = null;
		// }

		/*
		 * if (_cdrHelper != null) { _cdrHelper = null; }
		 */

		super.onDestroy();
	}

	public void sendCdrInfo()
	{
		// if (_cdrHelper != null)
		// {
		// if(!_isTradingTime || ((ITDLApplication)
		// getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay )
		// {
		// return; //don't send the cdr info if it is free
		// }
		//
		// try
		// {
		// String userId = this.getUser();
		// String account = getSessionAccount();
		// account = account.substring(0, account.length() - 2);
		// String deviceId = this.getDeviceId();
		// String dvcTime = /*CdrHelper.DVC_TIME;*/DateUtils.formatDate(new
		// Date(), CdrHelper.YEAR_MONTH_DAT_TIME_FORMAT);
		// String dvcType = String.valueOf(CommonDefn.DEVICE_TYPE);
		// String sessionEndTime = DateUtils.formatDate(new Date(),
		// CdrHelper.YEAR_MONTH_DAT_TIME_FORMAT);
		// String sessionStartTime = DateUtils.formatDate(_cdrHelper._startTime,
		// CdrHelper.YEAR_MONTH_DAT_TIME_FORMAT);
		// String svcInfo = /*CommonDefn.TDSTOCK_VERSION*/ getAppVersion() + "/"
		// + android.os.Build.VERSION.RELEASE;
		// String svcSubType = CdrHelper.SVC_SUB_TYPE;
		// String svcTime = String.valueOf(_isTradingTime ?
		// _cdrHelper._cdrCounter : 0);
		// String svcCount = CdrHelper.SVC_COUNT;
		// String seqNo = String.valueOf(_cdrHelper.getNextSeqNo());
		// String svcType = CdrHelper.SVC_TYPE;
		// /*String lsTime = DateUtils.formatDate(_cdrHelper._startTime,
		// CdrHelper.YEAR_MONTH_DAT_TIME_FORMAT);*/
		// String lsTime = /*DateUtils.formatDate(_cdrHelper._startTime,
		// CdrHelper.YEAR_MONTH_DAT_TIME_FORMAT);*/
		// _cdrHelper._lsTime;
		//
		// Log.e(TAG,
		// String.format("%s, %s,%s, %s,%s, %s,%s, %s,%s, %s,%s, %s,%s, %s,",
		// userId, account, deviceId, dvcTime, dvcType, sessionEndTime,
		// sessionStartTime, svcInfo, svcSubType,
		// svcTime, svcCount, seqNo, svcType, lsTime));
		// boolean postResult = _cdrHelper.postCdrCounterToServer(userId,
		// account, deviceId, dvcTime, dvcType, sessionEndTime,
		// sessionStartTime, svcInfo, svcSubType, svcTime, svcCount,
		// seqNo, svcType, lsTime);
		// Log.e(TAG, "post cdr msg to server, and the result is " + (postResult
		// ? "true" : "false"));
		// _cdrHelper.saveCdrCounter(true);
		// _cdrHelper._isStopFlag = true;
		//
		// }
		// catch (Exception e)
		// {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
	}

	/* Andy */
	// public synchronized void exitApp()
	// {
	// sendCdrInfo(); //this exit entry is coming from hiting cancel key
	// super.exitApp();
	//
	// }

	private void resetSyncServerTimeForDelayMode()
	{
		if (_server_time != null)
		{

			if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
			{
				_server_time.setTextColor(Color.YELLOW);
				_server_time.setText(Html.fromHtml(DELAY_TIPS));
			}

		}

	}

	/*
	 * private void resetQueueForDelayMode() { if(
	 * ((ITDLApplication)getApplicationContext()).getDataMode() ==
	 * CommonDefn.DataMode.Delay) { TextView queue_code =
	 * (TextView)findViewById(R.id.queue_ask_code); TextView queue_name =
	 * (TextView)findViewById(R.id.queue_ask_name);
	 * queue_code.setTextColor(Color.BLACK);
	 * queue_name.setTextColor(Color.BLACK); } }
	 */

	private void resetBrokerQueueForDelayMode()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			TextView queue = (TextView) findViewById(R.id.txt_broker_queue_code);
			queue.setText(Html.fromHtml(DELAY_TIPS_BROKER_QUEUE));
			queue.setVisibility(View.VISIBLE);

			BrokerQueueSampleByDelayMode();
		}
	}

	private void resetStockTradetickerForDelayMode()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			TextView queue = (TextView) findViewById(R.id.txt_stock_tradeticker);
			queue.setText(Html.fromHtml(DELAY_TIPS_STOCK_TRADETICKER_QUEUE));
			queue.setVisibility(View.VISIBLE);

			TradeTicketSampleByDelayMode();
		}
	}

	private void resetMarketDepthForDelayMode()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() == CommonDefn.DataMode.Delay)
		{
			TextView queue = (TextView) findViewById(R.id.txt_market_depth);
			queue.setText(Html.fromHtml(DELAY_TIPS_STOCK_MARKET_DEPTH));
			queue.setVisibility(View.VISIBLE);

			// if (_current_stock_ask_queue_1 != null)
			// {
			// _current_stock_ask_queue_1.setText(Html.fromHtml(BRACKET));
			// }
			// if (_current_stock_ask_queue_2 != null)
			// {
			// _current_stock_ask_queue_2.setText(Html.fromHtml(BRACKET));
			// }
			// if (_current_stock_ask_queue_3 != null)
			// {
			// _current_stock_ask_queue_3.setText(Html.fromHtml(BRACKET));
			// }
			// if (_current_stock_ask_queue_4 != null)
			// {
			// _current_stock_ask_queue_4.setText(Html.fromHtml(BRACKET));
			// }
			// if (_current_stock_ask_queue_5 != null)
			// {
			// _current_stock_ask_queue_5.setText(Html.fromHtml(BRACKET));
			// }
			MarketDepthSampleByDelayMode();
		}

	}

	private void resetTradeTicker()
	{
		if (((ITDLApplication) getApplicationContext()).getDataMode() != CommonDefn.DataMode.Delay)
		{
			int row = _tradeticker_textviews.length;
			int col = _tradeticker_textviews[0].length;
			for (int line = 0; line < row; line++)
			{
				for (int column = 0; column < col; column++)
				{
					_tradeticker_textviews[line][column].setText("");
					// modified by haibo, 2011-06-20, no need to do so and it
					// cause the anr.
					// _tradeticker_textviews[line][column].postInvalidate();
				}
			}
		}
	}

	/* Andy */
	// private class CallbackHandlerOnSyncTradingTime implements
	// LightStreamerHandlerInterface
	// {
	// final String TRUE = "true";
	// private boolean _isPostedDataWhenIsNotTradingTime = false;
	//
	// public void onUpdate(int itemPos, String itemName, final UpdateInfo
	// update)
	// {
	// try
	// {
	// _isTradingTime =
	// TRUE.equalsIgnoreCase(update.getNewValue(HolidayInfo.FIELD));
	//
	// // _cdrHelper._isPause = _isTradingTime ? false : true; //set pause if is
	// not trading time
	// /*if(_isTradingTime ) {
	// _isPostedDataWhenIsNotTradingTime = false;
	// }
	// else {
	// if(!_isPostedDataWhenIsNotTradingTime ) {
	// sendCdrInfo(); //send cdr info if got the leave time
	// }
	// _isPostedDataWhenIsNotTradingTime = true;
	// }*/
	//
	//
	// // Log.d(TAG, "is trading time:" + update.getNewValue(HolidayInfo.FIELD)
	// );
	// }
	// catch (Exception e)
	// {
	// e.printStackTrace();
	// }
	// }
	// }

	/* Andy */
	// private class RePostCdrTask extends AsyncTask<String, Void, Void>
	// {
	// @Override
	// protected Void doInBackground(String... params)
	// {
	// /*if (_cdrHelper != null)
	// {
	// _cdrHelper.rePostCdrFromLocal();
	// }*/
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result)
	// {
	// super.onPostExecute(result);
	// }
	//
	// }

	/* Andy */
	// private class SubscribeOthersTask extends AsyncTask<String, Void, Void>
	// {
	//
	// @Override
	// protected Void doInBackground(String... params)
	// {
	// subscribeOthers();
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(Void result)
	// {
	// super.onPostExecute(result);
	// }
	// }

	private void subscribeOthers()
	{
		try
		{
			TDStockLog.d(TAG, "subscribeOthers: first !");

			if (_callbackHandlerOnIndex == null)
				_callbackHandlerOnIndex = new CallbackHandlerOnIndex();

			/*
			 * _subscrRefs.addAll(Arrays.asList(subscribeMultiple(_myClient, new
			 * String[] { INDEX_NAME_HSI, INDEX_NAME_HSCEI }, new String[] {
			 * IndexInfo.INDEXLAST, IndexInfo.INDEXNET, IndexInfo.TURNOVER,
			 * IndexInfo.INDEXNETPRECENTAGE }, IndexInfo.ADAPTER,
			 * _callbackHandlerOnIndex))); //modified by haibo on 2011-07-13 ,
			 * use batch request instead of single request
			 */

			List<String> iIdList = new ArrayList<String>();
			List<LS_SubscriptionItem> iItemList = new ArrayList<LS_SubscriptionItem>();
			List<ILS_UserClient_Response> iResponseList = new ArrayList<ILS_UserClient_Response>();

			LS_SubscriptionItem interestItem = new LS_SubscriptionItem(
					IndexInfo.ADAPTER);
			interestItem.AddSubscribeItem(INDEX_NAME_HSI);
			interestItem.AddSubscribeItem(INDEX_NAME_HSCEI);
			interestItem.AddSubscribeSchema(IndexInfo.INDEXLAST);
			interestItem.AddSubscribeSchema(IndexInfo.INDEXNET);
			interestItem.AddSubscribeSchema(IndexInfo.TURNOVER);
			interestItem.AddSubscribeSchema(IndexInfo.INDEXNETPRECENTAGE);

			/*
			 * IDENTIFIER_1 = LSGetUniqueID(); if
			 * (LightStreamerSubscribeItem(IDENTIFIER_1, interestItem,this)) { }
			 */
			iIdList.add(IDENTIFIER_1);
			iItemList.add(interestItem);
			iResponseList.add(this);

			// Thread.yield();

			/*
			 * Log.d(TAG, "subscribeOthers: second !"); //
			 * _subscrRefs.add(subscribeIndexFutures(_myClient)); //subscribe
			 * the index futures information
			 * _subscrRefs.addAll(Arrays.asList(subscribeMultiple(_myClient, new
			 * String[] { INDEX_FUTURES_HSI_1, INDEX_FUTURES_HSI_2 }, new
			 * String[] { IndexFuturesInfo.LAST, IndexFuturesInfo.NET },
			 * IndexFuturesInfo.ADAPTER, _callbackHandlerOnIndexFutures)));
			 * //modified by haibo on 2011-07-13 , use batch request instead of
			 * single request
			 */
			if (_callbackHandlerOnIndexFutures == null)
			{
				_callbackHandlerOnIndexFutures = new CallbackHandlerOnIndexFutures();
			}

			LS_SubscriptionItem indexFuturesItem = new LS_SubscriptionItem(
			/*
			 * IndexFuturesInfo. ADAPTER
			 */_indexFuturesAdapter);
			indexFuturesItem.AddSubscribeItem(INDEX_FUTURES_HSI_1);
			indexFuturesItem.AddSubscribeItem(INDEX_FUTURES_HSI_2);
			indexFuturesItem.AddSubscribeSchema(IndexFuturesInfo.LAST);
			indexFuturesItem.AddSubscribeSchema(IndexFuturesInfo.NET);

			/*
			 * IDENTIFIER_2 = LSGetUniqueID(); if
			 * (LightStreamerSubscribeItem(IDENTIFIER_2, indexFuturesItem,this))
			 * { } Thread.yield();
			 */

			iIdList.add(IDENTIFIER_2);
			iItemList.add(indexFuturesItem);
			iResponseList.add(this);

			/*
			 * _subscrRefs.addAll(Arrays.asList(subscribeMultiple(_myClient, new
			 * String[] { WORLDINDEX_SSE1 }, new String[] { WorldIndexInfo.LAST,
			 * WorldIndexInfo.NET }, WorldIndexInfo.ADAPTER,
			 * _callbackHandlerOnWorldIndex))); //modified by haibo on
			 * 2011-07-13 , use batch request instead of single request
			 */

			if (_callbackHandlerOnWorldIndex == null)
			{
				_callbackHandlerOnWorldIndex = new CallbackHandlerOnWorldIndex();
			}

			LS_SubscriptionItem worldIndexItem = new LS_SubscriptionItem(
			/*
			 * WorldIndexInfo. ADAPTER
			 */_indexSSEIAdapter);
			worldIndexItem.AddSubscribeItem(WORLDINDEX_SSE1);
			worldIndexItem.AddSubscribeSchema(WorldIndexInfo.LAST);
			worldIndexItem.AddSubscribeSchema(WorldIndexInfo.NET);

			/*
			 * IDENTIFIER_3 = LSGetUniqueID(); if
			 * (LightStreamerSubscribeItem(IDENTIFIER_3, worldIndexItem,this)) {
			 * } Thread.yield();
			 */

			iIdList.add(IDENTIFIER_3);
			iItemList.add(worldIndexItem);
			iResponseList.add(this);

			TDStockLog.d(TAG, "have subscribed the items for SSE1!");

			// Thread.yield();
			TDStockLog.d(TAG, "subscribeOthers: the left !");
			// _subscrRefs.add(subscribeServerTimeStamp(_myClient)); //subscribe
			// the server time stamp

			if (((ITDLApplication) getApplicationContext()).getDataMode() != CommonDefn.DataMode.Delay)
			{
				if (_callbackHandlerOnTimeServer == null)
				{
					_callbackHandlerOnTimeServer = new CallbackHandlerOnTimeServer();
				}

				/*
				 * _subscrRefs.addAll(Arrays.asList(subscribeMultiple(_myClient,
				 * TimestampInfo.SUBSCRIBE_ITEMS, new String[] {
				 * TimestampInfo.FIELD }, TimestampInfo.ADAPTER,
				 * _callbackHandlerOnTimeServer))); //modified by haibo on
				 * 2011-07-13 , use batch request instead of single request
				 */

				LS_SubscriptionItem serverTimeItem = new LS_SubscriptionItem(
						TimestampInfo.ADAPTER);
				for (String item : TimestampInfo.SUBSCRIBE_ITEMS)
					serverTimeItem.AddSubscribeItem(item);
				serverTimeItem.AddSubscribeSchema(TimestampInfo.FIELD);

				/*
				 * IDENTIFIER_4 = LSGetUniqueID(); if
				 * (LightStreamerSubscribeItem(IDENTIFIER_4,
				 * serverTimeItem,this)) { }
				 */

				iIdList.add(IDENTIFIER_4);
				iItemList.add(serverTimeItem);
				iResponseList.add(this);

				// Thread.yield();
				TDStockLog.d(TAG,
						"have subscribed the items for server time!");
				/* Andy */
				// if (_callbackHandlerOnSyncTradingTime == null)
				// {
				// _callbackHandlerOnSyncTradingTime = new
				// CallbackHandlerOnSyncTradingTime();
				// }

				/*
				 * _subscrRefs.addAll(Arrays.asList(subscribeMultiple(_myClient,
				 * HolidayInfo.SUBSCRIBE_ITEMS, new String[] { HolidayInfo.FIELD
				 * }, HolidayInfo.ADAPTER,
				 * _callbackHandlerOnSyncTradingTime)));; //modified by haibo on
				 * 2011-07-13 , use batch request instead of single request
				 */

				/* Andy */
				// LS_SubscriptionItem tradingTimeItem = new
				// LS_SubscriptionItem(TimestampInfo.ADAPTER);
				// for(String item : HolidayInfo.SUBSCRIBE_ITEMS)
				// tradingTimeItem.AddSubscribeItem(item);
				// tradingTimeItem.AddSubscribeSchema(HolidayInfo.FIELD) ;

				/*
				 * IDENTIFIER_5 = LSGetUniqueID(); if
				 * (LightStreamerSubscribeItem(IDENTIFIER_5,
				 * tradingTimeItem,this)) { }
				 */

				/* Andy */
				// iIdList.add(IDENTIFIER_5);
				// temList.add(tradingTimeItem);
				// iResponseList.add(this);
				// Log.d(TAG, "have subscribed the items for holiday!");
			}

			LightStreamerSubscribeItemsInBatch(iIdList, iItemList,
					iResponseList);

		}
		catch (Exception e)
		{
			TDStockLog.d(TAG,
					"error happened in the process of the subscribeOthers:"
							+ (e.getMessage() == null ? ""
									: "subscribe other items error"
											+ e.getMessage()));
		}

	}

	/* Andy */
	// public void onCdrPause()
	// {
	// /*if (_cdrHelper != null)
	// {
	// _cdrHelper._isPause = true;
	// }*/
	// }
	//
	// public void onCdrResume()
	// {
	// /* if (_cdrHelper != null)
	// {
	// _cdrHelper._isPause = false;
	// }*/
	// }
	//
	// public void onCdrCounterComeTo15Minutes()
	// {
	// sendCdrInfo();
	// }

	@Override
	protected boolean forwardToChartActivity()
	{
		// TODO Auto-generated method stub
		forwardToNvChart();

		return true;
	}

	@Override
	public void onBackPressed()
	{
		// super.onBackPressed();
		if (container_input != null)
		{
			if (container_input.getVisibility() != View.GONE)
			{
				container_input.startAnimation(anim_up);
				_current_stock_code.setText(lastStockCode);
				_current_stock_code.setSelection(_current_stock_code
						.getText().toString().length());
				return;
			}
		}

		handleExitApplication();
	}

	private void hightLightChangeItems(Object lastNominalValue,
			String nominalValue, String netValue)
	{
		double lastValue = CommonDefn.APPROACH_ZERO;
		double currentValue = 0.00d;
		double net_value = 0.00d;
		try
		{
			lastValue = Double.parseDouble(lastNominalValue == null ? "0.00"
					: lastNominalValue.toString());
			currentValue = Double.parseDouble(nominalValue);
			net_value = Double.parseDouble(netValue);

			TDStockLog.d(TAG, String.format(
					"last=%f, current=%f, netValue=%s", lastValue,
					currentValue, net_value));
		}
		catch (Exception e)
		{
			lastValue = 0.00d;
		}

		int color = CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN;
		if (lastNominalValue == null
				|| (Math.abs(lastValue - CommonDefn.APPROACH_ZERO) <= CommonDefn.APPROACH_ZERO))
		{
			color = (net_value >= 0.00d) ? CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN
					: CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_ORANGE;
		}
		else
		{
			color = (currentValue > lastValue) ? CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_GREEN
					: CommonDefn.MONITOR_HIGHLIGHT_BACKGROUND_ORANGE;
		}

		final int highlightColor = color; /*
										 * ( ( Math.abs(lastValue -
										 * CommonDefn.APPROACH_ZERO) <=
										 * CommonDefn.APPROACH_ZERO && net_value
										 * >= 0) || (currentValue - lastValue
										 * >0) ) ?CommonDefn.
										 * MONITOR_HIGHLIGHT_BACKGROUND_GREEN :
										 * CommonDefn
										 * .MONITOR_HIGHLIGHT_BACKGROUND_ORANGE
										 * ;
										 */
		final Runnable changeBg = new Runnable()
		{
			@Override
			public void run()
			{
				_current_stock_nominal.setBackgroundColor(highlightColor);
				_current_stock_net.setBackgroundColor(highlightColor);
				_current_stock_net_percentage
						.setBackgroundColor(highlightColor);
				// modify by ouyangzhihui 2011-06-28
				_current_stock_net.setTextColor(Color.BLACK);
				_current_stock_net_percentage.setTextColor(Color.BLACK);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_nominal.postInvalidate();
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_net.postInvalidate();
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_net_percentage.postInvalidate();
			}

		};

		final Runnable reStoreBg = new Runnable()
		{
			@Override
			public void run()
			{
				_current_stock_nominal.setBackgroundDrawable(null);
				_current_stock_net.setBackgroundDrawable(null);
				_current_stock_net_percentage.setBackgroundDrawable(null);
				// modify by ouyangzhihui 2011-06-28
				_current_stock_net
						.setTextColor(_current_stock_net.getText()
								.toString().indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
				_current_stock_net_percentage
						.setTextColor(_current_stock_net_percentage
								.getText().toString().indexOf("-") >= 0 ? Color.RED
								: Color.GREEN);
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_nominal.postInvalidate();
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_net.postInvalidate();
				// modified by haibo, 2011-06-20, no need to do so and it cause
				// the anr. _current_stock_net_percentage.postInvalidate();
			}

		};

		new Thread()
		{
			@Override
			public void run()
			{
				_messageHandler.post(changeBg);
				_messageHandler.postDelayed(reStoreBg, 1000);
			}

		}.start();

	}

	/* Andy */
	// @Override
	// public void finish()
	// {
	// super.finish();
	// Log.d(TAG, "on finish() executed!");
	// if(((ITDLApplication) getApplicationContext()).getCdrSender() == null )
	// {
	// /*if (_cdrHelper != null)
	// {
	// this.sendCdrInfo();
	// }*/
	// }
	//
	// }

	/*
	 * private void setPDeviceId() { String pdeviceId =
	 * _prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
	 * if(pdeviceId.trim().length() < 2) new
	 * PDeviceIdAsyncTask(CurrentStockInfoActivity.this).execute(); } private
	 * class PDeviceIdAsyncTask extends AsyncTask<String, Void, Void> { private
	 * Context _context; private String _deviceId; private SharedPreferences
	 * preferences; private String pdeviceid; public PDeviceIdAsyncTask(Context
	 * context) { this._context = context; preferences =
	 * getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING,
	 * Context.MODE_PRIVATE); }
	 * 
	 * @Override protected void onPreExecute() { super.onPreExecute();
	 * if(preferences == null) preferences =
	 * getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING,
	 * Context.MODE_PRIVATE); pdeviceid =
	 * preferences.getString(CommonDefn.PREFERENCE_DEVICE_ID, ""); }
	 * 
	 * @Override protected Void doInBackground(String... params) {
	 * if(pdeviceid.length() <= 1) { int i = 0; do { if(i >= 3) break; _deviceId
	 * = SystemInfo.getDeviceId(_context); i++; } // mac address is empty
	 * while(SystemInfo
	 * .EMPTY_WIFI_MAC_ADDRESS.equals(SystemInfo.current_wifi_mac_address)); }
	 * return null; }
	 * 
	 * @Override protected void onPostExecute(Void result) {
	 * super.onPostExecute(result); // if pdevicei is empty save deviceid
	 * if(pdeviceid.length() <= 1) {
	 * preferences.edit().putString(CommonDefn.PREFERENCE_DEVICE_ID,
	 * _deviceId).commit(); // Log.d(TAG,
	 * "pdeviceId="+preferences.getString(CommonDefn.PREFERENCE_DEVICE_ID, ""));
	 * } } }
	 */

	/* Andy */
	// @Override
	// public ActivityGroupController GetActivityController()
	// {
	// return StockGroup.GetActivityGroupHostControl();
	// }

	/* Andy */
	@Override
	protected ActivityGroupController GetActivityGroupController()
	{
		return StockGroup.GetActivityGroupHostControl();
	}

	/* Andy */
	// @Override
	// protected void onStop() {
	// Log.d(TAG, "on Stop executed!");
	// super.onStop();
	// }

	/* Andy */
	// @Override
	// public void LS_UserClient_ConnectionReport(CONNECTION_STATUS iStatus)
	// {
	// Log.i(TAG, "LS_UserClient_ConnectionReport: " + iStatus);
	// super.LS_UserClient_ConnectionReport(iStatus);
	// }

	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
		super.onUpdate(iIdentifier, iSchemaIndex, iSchemaValue, iUpdateInfo);

		if (IDENTIFIER_0.equals(iIdentifier))
		{
			try
			{
				TDStockLog.d(TAG, "begin to update stock info!");
				_callBackHandlerOnStock.onUpdate(iSchemaIndex,
						iSchemaValue, iUpdateInfo);
				TDStockLog.d(TAG, "update stock info successfully!");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				TDStockLog.e(TAG, e.toString());
			}

			/*
			 * if( sunFlowerView1 != null && sunFlowerView1.isRunning()) {
			 * stopSunflower(); }
			 */

		}
		else if (IDENTIFIER_1.equals(iIdentifier))
		{
			_callbackHandlerOnIndex.onUpdate(iSchemaIndex, iSchemaValue,
					iUpdateInfo);
		}
		else if (IDENTIFIER_2.equals(iIdentifier))
		{
			_callbackHandlerOnIndexFutures.onUpdate(iSchemaIndex,
					iSchemaValue, iUpdateInfo);
		}
		else if (IDENTIFIER_3.equals(iIdentifier))
		{
			_callbackHandlerOnWorldIndex.onUpdate(iSchemaIndex,
					iSchemaValue, iUpdateInfo);
		}
		else if (IDENTIFIER_4.equals(iIdentifier))
		{
			_callbackHandlerOnTimeServer.onUpdate(iSchemaIndex,
					iSchemaValue, iUpdateInfo);
		}
		/* Andy */
		// else if(IDENTIFIER_5.equals(iIdentifier) )
		// {
		// _callbackHandlerOnSyncTradingTime.onUpdate(iSchemaIndex,
		// iSchemaValue, iUpdateInfo);
		// }
	}

	Trade_StockViewInfoItem	curViewStockInfo	= null;

	private void setlinkToTrading()
	{
		if (TradeAppInfo.TradeApp_Ready == false)
			return;

		findViewById(R.id.current_stock_bid).setOnClickListener(
				tradeEnterListener);
		findViewById(R.id.current_stock_ask).setOnClickListener(
				tradeEnterListener);
	}

	private void PlaceSwitchTradeOrderKeyPad(
			Trade_StockViewInfoItem iStockInfo, String iOrderSide,
			String iPrice)
	{
		// When an OK is pressed, we will start the keypad with available
		// information
		Intent intentObj;

		Trade_StockReqOrderItem transferObj;

		intentObj = new Intent(actContext, Trade_OrderKeypadActivity.class);

		// Provide with no order no
		transferObj = new Trade_StockReqOrderItem("", iStockInfo.stockCode,
				iStockInfo.chnName, iStockInfo.engName);
		// The outstanding is the remaining quantity for order
		transferObj.SetOrderQuantity("0", "0", iStockInfo.stepVolume);

		// Assume it is a buy
		transferObj.SetOrderSide(iOrderSide);
		transferObj.SetOrderPrice(iPrice);
		transferObj.SetCurrencyCode(iStockInfo.currencyCode);
		transferObj.SetOrderType("E");

		// Place the Order info, then the Stock View Info
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo,
				transferObj);
		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iStockInfo);

		// Since we are directly enter, flush the memory
		TradeAppInfo.SetStockViewInfoItem(null);
		// Place the bundle object to the intent
		SwitchActivityFromHost(Trade_OrderKeypadActivity.class, intentObj);
	}

	private boolean		isGettingStockQuote	= false;
	private OnClickListener	tradeEnterListener	= new OnClickListener()
										{
											@Override
											public void onClick(
													View iViewObj)
											{
												int objId;
												boolean isDemoOnly;

												if (curViewStockInfo == null)
													return;

												if (isGettingStockQuote == true)
													return;

												objId = iViewObj
														.getId();
												// Allow for testing
												// environment
												isDemoOnly = TradeAppInfo
														.IsAllowDemoOnly(appHost
																.GetLSClient_ServicePlan());
												if (debugMode)
													TDStockLog.i(
															TAG,
															"TradeApp isDemoOnly: "
																	+ isDemoOnly);

												// If it is a demo
												// account, it must be
												// relogon
												Class<? extends Activity> primaryAct;

												primaryAct = appHost.actListController
														.GetCurrentActivityClass();

												// Set our primary
												// return class
												TradeAppInfo
														.SetPrimaryEntryClass(primaryAct);

												String orderSideString;
												String priceString;

												switch (objId)
												{
													case R.id.current_stock_ask:
														orderSideString = Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK;
														priceString = curViewStockInfo
																.GetCurBidPriceText();
														break;
													default:
														orderSideString = Trade_StockReqOrderItem.TRANSACTIONTYPE_BID;
														priceString = curViewStockInfo
																.GetCurAskPriceText();
														break;
												}

												// Set the Information for
												// KeyPad Viewing
												TradeAppInfo
														.SetStockViewInfoItem(
																curViewStockInfo,
																orderSideString);
												TradeAppInfo
														.SetAsBMPMode(appHost
																.IsBMPMode());

												/* Andy */
												// //Enfroce for BMP Mode
												// if (appHost.IsBMPMode())
												// {
												// TradeAppInfo.SetAsBMPMode(false);
												// isDemoOnly = true;
												// }

												// If it is a demo only
												// flag, and user was not in
												// demo mode, reset
												// the registration
												if (isDemoOnly)
												{
													TradeAppInfo
															.SetAsDemoAccount(true);
													TradeAppInfo
															.SetTradingRegistration(false);
													SwitchActivityFromHost(Trade_LoginActivity.class);
													return;
												}

												// Provide a method for use
												// to escape from Demo Mode
												if (TradeAppInfo
														.IsDemoAccount())
												{
													TradeAppInfo
															.SetAsDemoAccount(false);
													TradeAppInfo
															.SetTradingRegistration(false);
													SwitchActivityFromHost(Trade_LoginActivity.class);
													return;
												}

												TradeAppInfo
														.SetAsDemoAccount(false);

												if (TradeAppInfo
														.IsTradingRegistered())
												{
													if ((curViewStockInfo == null)
															|| !TradeAppInfo.TradeKeySwap_Ready)
													{
														SwitchActivityFromHost(Trade_tradingOptionActivity.class);
														return;
													}

													// Try to download the
													// quote
													if (TradeAppInfo
															.IsBMPMode())
													{
														final TradeGetDetailStockQuote quoteRequest;
														final String iiOrderSide;
														final String iiOrderPrice;

														isGettingStockQuote = true;
														startSunflower();
														iiOrderSide = orderSideString;
														iiOrderPrice = priceString;
														quoteRequest = new TradeGetDetailStockQuote(
																actContext);
														quoteRequest
																.SetRequestQuoteInfo(
																		appHost.IsDevelopment(),
																		curViewStockInfo.stockCode,
																		appHost.GetLSClient_AccountLogonName(),
																		appHost.GetLSClient_SessionKey());
														quoteRequest
																.SendRequest(
																		TradeAppInfo
																				.IsDemoAccount(),
																		new ITradeGetStockQuoteResponse()
																		{
																			@Override
																			public void ResponseFunc(
																					boolean iSuccessfulSend,
																					TradeGetStockQuoteResult iResponse)
																			{
																				isGettingStockQuote = false;
																				stopSunflower();
																				quoteRequest
																						.Dispose();
																				if (iSuccessfulSend == false)
																				{

																					new CustomizeDialog(
																							getMyOwnContext(),
																							getString(R.string.info),
																							getString(R.string.commErrorText),
																							getString(R.string.ok))
																							.show();
																					return;
																				}

																				if (!iResponse.resultCode
																						.equals("0"))
																				{
																					if (iResponse.resultCode
																							.equals("-1"))
																						appHost.LS_Client_ResetConnection();

																					String textValue;

																					textValue = iResponse.errorMessage;
																					if (textValue
																							.equals(""))
																						textValue = getString(R.string.commErrorText);

																					new CustomizeDialog(
																							getMyOwnContext(),
																							getString(R.string.info),
																							textValue,
																							getString(R.string.ok))
																							.show();
																					return;
																				}
																				PlaceSwitchTradeOrderKeyPad(
																						iResponse.stockQuoteItem,
																						iiOrderSide,
																						iiOrderPrice);

																			}
																		});
														return;
													}

													// When an OK is
													// pressed, we will
													// start the keypad with
													// available
													// information
													PlaceSwitchTradeOrderKeyPad(
															curViewStockInfo,
															orderSideString,
															priceString);
													return;
												}

												// A Brand new logon
												TradeAppInfo
														.SetAsDemoAccount(false);
												SwitchActivityFromHost(Trade_LoginActivity.class);
												return;
											}
										};

	private void MarketDepthSampleByDelayMode()
	{
		try
		{
			_current_stock_bid_share_1.setText("73.2K");
			_current_stock_bid_queue_1.setText("(13)");

			_current_stock_bid_share_2.setText("134.8K");
			_current_stock_bid_queue_2.setText("(10)");

			_current_stock_bid_share_3.setText("33.6K");
			_current_stock_bid_queue_3.setText("(6)");

			_current_stock_bid_share_4.setText("80.8K");
			_current_stock_bid_queue_4.setText("(17)");

			_current_stock_bid_share_5.setText("89.6K");
			_current_stock_bid_queue_5.setText("(8)");

			_current_stock_ask_share_1.setText("150K");
			_current_stock_ask_queue_1.setText("(12)");

			_current_stock_ask_share_2.setText("176.8K");
			_current_stock_ask_queue_2.setText("(23)");

			_current_stock_ask_share_3.setText("342.8K");
			_current_stock_ask_queue_3.setText("(76)");

			_current_stock_ask_share_4.setText("70.8K");
			_current_stock_ask_queue_4.setText("(21)");

			_current_stock_ask_share_5.setText("260.8K");
			_current_stock_ask_queue_5.setText("(86)");
		}
		catch (Exception e)
		{
		}
	}

	private void TradeTicketSampleByDelayMode()
	{
		String[][] arr = { { "11:39", "1.6K", "61.55", "B" },
				{ "11:39X", "400", "61.45", "U" },
				{ "11:39X", "8.8K", "61.45", "U" },
				{ "11:39", "1.2K", "61.60", "A" },
				{ "11:38", "1.2K", "61.55", "B" } };

		for (int i = 0; i < _tradeticker_textviews.length; i++)
		{
			for (int j = 0; j < _tradeticker_textviews[i].length; j++)
			{
				_tradeticker_textviews[i][j].setText(arr[i][j]);
			}
		}
	}

	private void BrokerQueueSampleByDelayMode()
	{
		String tmp1 = "4975^4977^1197^1197^2045^-1^4068^9028^9059^9059^-2^9047^1799^1569^2076^1197^4066^4066^9066^9059^4978^4085^-3^4163^1096^3448^4977^1438^-4^7184^2076^1197^4977^-5^4625^8699^-6^2075^1197^4066^-7^-8^-9^-10^-11^-12^-13^-14^-15^-16^-17^-18^-19^";
		String tmp2 = "4978^+1^9032^8577^8575^4977^+2^8575^4978^+3^4978^4988^4977^+4^8146^8578^8009^4977^+5^8127^8189^4978^1496^+6^5529^9421^4656^2277^8135^7174^4977^3077^5465^5466^5468^5469^+7^8577^+8^2328^+9^+10^+11^+12^+13^+14^+15^+16^+17^+18^+19^";
		String tmp3 = "法國興業^法國興業^Credit Su^Credit Su^巴克萊亞^-1^法國巴黎^UBS Sec^UBS Sec^UBS Sec^-2^永隆^耀才^電訊數碼^巴克萊亞^Credit Su^法國巴黎^法國巴黎^UBS Sec^UBS Sec^法國興業^Credit Su^-3^麥格理資^東盛證券^高盛^法國興業^Susqueh^-4^德意志^巴克萊亞^Credit Su^法國興業^-5^致富^法國巴黎^-6^巴克萊亞^Credit Su^法國巴黎^-7^-8^-9^-10^-11^-12^-13^-14^-15^-16^-17^-18^-19^";
		String tmp4 = "法國興業^+1^招商^匯豐^匯豐^法國興業^+2^匯豐^法國興業^+3^法國興業^J.P. Morg^法國興業^+4^中銀國際^匯豐^協聯^法國興業^+5^中銀國際^中銀國際^法國興業^Optiver T^+6^新鴻基投^恆生^致富^恆生^中銀國際^匯富金融^法國興業^Morgan ^Morgan ^Morgan ^Morgan ^Morgan ^+7^匯豐^+8^周生生^+9^+10^+11^+12^+13^+14^+15^+16^+17^+18^+19^";
		update_BID_QUEUE(tmp1, _BID_LEFT_TEXTVIEWS, _BID_RIGHT_TEXTVIEWS);
		update_ASK_QUEUE(tmp2, _ASK_LEFT_TEXTVIEWS, _ASK_RIGHT_TEXTVIEWS);

		update_BID_QUEUE(tmp3, _BID_LEFT_TEXTVIEWS_CH,
				_BID_RIGHT_TEXTVIEWS_CH);
		update_ASK_QUEUE(tmp4, _ASK_LEFT_TEXTVIEWS_CH,
				_ASK_RIGHT_TEXTVIEWS_CH);
	}

	@Override
	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo)
	{
		if (iNetInfo.isAvailable() || iNetInfo.isConnected())
		{
			WebViewHelper.showAd(this, (WebView) findViewById(R.id.webView));
		}
	}

	private String DealwithNull(String tmp)
	{
		if (tmp == null)
			return CommonDefn.DEFAULT_FIELD_VALUE;
		else
			return tmp;
	}
}
